Public Chat in Java [Using Multiple Clients and a Server]

This is the implementation of public chat in java where the user can chat with each other the server maintains the connection with all the clients

Client:
bclient.java
[cc lang=”java”]
import java.io.*;
import java.net.*;

public class bclient implements Runnable
{
Socket sock;
Thread tn,tk;
BufferedReader ink,inn;
PrintWriter ptn;
String str;
bclient()
{
try
{
sock=new Socket(“127.0.0.1”,1234);
ink=new BufferedReader(new InputStreamReader(System.in));
inn=new BufferedReader(new InputStreamReader(sock.getInputStream()));
ptn=new PrintWriter(sock.getOutputStream(),true);
System.out.println(“Client Started”);
}
catch(Exception e){}
tk=null;
tn=null;
}
public void run()
{
if(Thread.currentThread()==tk)
{
do
{
try
{
str=ink.readLine();
ptn.println(str);
}
catch(Exception e){}
}
while(true);
}
else if(Thread.currentThread()==tn)
{
do
{
try
{

str=inn.readLine();
System.out.println(str);}
catch(Exception e){}
}
while(true);
}
}
public static void main(String[] args)
{
bclient bc=new bclient();
bc.tk=new Thread(bc);
bc.tn=new Thread(bc);
bc.tk.start();
bc.tn.start();
}
}

[/cc]

Server:
bserver.java
[cc lang=”java”]
import java.io.*;
import java.net.*;

public class bserver implements Runnable
//public class bserver extends Thread
{
ServerSocket ss;
Socket sock[]=new Socket[20];
Thread t[]=new Thread[20];
Thread taccept;
BufferedReader br;
int count=0;
PrintWriter pt;
String str=”hello”;
bserver()
{

try
{
ss=new ServerSocket(1234);
System.out.println(“Server Started”);
}
catch(Exception e){}
taccept=null;
count=0;
}
public void run()
{
if(Thread.currentThread()==taccept){
do
{
try
{
System.out.println(“New Connection Establishing…”);
sock[count]=ss.accept();
t[count]=new Thread(this);
System.out.println(“Class”+count);
t[count].start();
count++;
}
catch(Exception e){}

}
while(true);
}
else
{
for(int i=0;i

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *