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
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();
}
}
Server:
bserver.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<count;i++)
if(Thread.currentThread()==t[i])
{
do
{
try
{
System.out.println("Getting Input from an active thread..");
br=new BufferedReader(new InputStreamReader(sock[i].getInputStream()));
str=br.readLine();
for(int j=0;j<count;j++)
{
if(i!=j)
{
System.out.println("Sending Input to client "+j);
pt=new PrintWriter(sock[j].getOutputStream(),true);
pt.println("Client"+i+":"+str);
}
}
}
catch(Exception e){}
}
while(true);
}
}
}
public static void main(String[] args)
{
bserver bs=new bserver();
bs.taccept=new Thread(bs);
bs.taccept.start();
}
}
Recent Comments