Client to Client Chat

 

Write a network program to perform a client to client chat between two clients. Either of the two clients can start a conversation at any time.

Server.java


import java.io.*;
import java.net.*;
class Server
{
	public static void main(String args[]) throws Exception
	{
		ServerSocket ss= new ServerSocket(7632);
		System.out.println("Server is waiting for two clients to 
											connect");
		Socket s1= ss.accept();
		System.out.println("The first client is connected.");
		Socket s2= ss.accept();
		System.out.println("All the clients are connected.");

		new Second(s1,s2);

		while(true)
		{
			BufferedReader br1=new BufferedReader(new 
					InputStreamReader(s1.getInputStream()));
			PrintWriter pr1= new 
						PrintWriter(s2.getOutputStream());
			String str=br1.readLine();
			String toClient2="Client 1: "+str;
			pr1.println(toClient2);
		}
	}
}
class Second implements Runnable 
{
	Socket s1,s2;
	Thread t;
	Second(Socket cli1, Socket cli2)
	{
		s1=cli1;
		s2=cli2;
		t= new Thread(this);
		t.start();
	}		
	public void run()
	{
		try
		{
			while(true)
			{
				BufferedReader br1=new BufferedReader(new 
InputStreamReader(s2.getInputStream()));
				PrintWriter pr1= new	
PrintWriter(s1.getOutputStream());
				String str=br1.readLine();
				String toClient2="Client 2: "+str;
				pr1.println(toClient2);
			}
		}
		catch(Exception e)
		{
			System.out.println("Error: "+e);
		}
	}
}



Client.java



import java.io.*;
import java.net.*;

class Client
{
	public static void main(String args[]) throws Exception
	{
		Socket s= new Socket("localhost",7632);
		System.out.println("Client is connected with the server.");
		new ToStream(s);	
		while(true)
		{
			BufferedReader br= new BufferedReader(new 
					InputStreamReader(s.getInputStream()));
			System.out.println(br.readLine());
		}
	}
}

class ToStream implements Runnable
{
	Socket ss;
	Thread t;
	ToStream(Socket s)
	{
		ss=s;
		t=new Thread(this);
		t.start();	
	}	

	public void run()
	{
		try
		{
			BufferedReader br=new BufferedReader(new 
							InputStreamReader(System.in));
			PrintWriter pr= new PrintWriter(ss.getOutputStream());
			while(true)
			{
				pr.println(br.readLine());
			}
		}
		catch(Exception e)
		{
			System.out.println(e);
		}
	}
} 




Output

 

 

Terminal 1 Terminal 2 Terminal 3
>java Server

> Server is waiting for two clients to connect.

 

> The first client is connected.

 

> The second client is connected.

> All the clients are connected.

 

 

 

 

 

>java Client

 

 

 

 

 

 

 

>Hello! How are you?

 

 

 

>Client2: Fine!

>Good Bye!

 

 

 

>Client2:Bye

 

 

 

 

 

>java Client

 

 

 

 

 

>Client 1: Hello! How are you?

 

>Fine!

 

 

>Client1: Good Bye!

>Bye

 

Leave a Reply

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