DreamsCoder.com

We Code your Dreams


home > Chat application using Socket programming in JAVA




Chat application using Socket programming in JAVA









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

public class chat_server
{
	
	public static void main(String[] args) {
		
	ServerSocket ss;  //Server 
	Socket client; // to accept clients request
	String nm;
	String msg,smsg;
	
	try
	{
	ss = new ServerSocket(1212);

	System.out.println("Server is Waitng For Client");
	client = ss.accept();

	System.out.println("Client is Connected ");

	BufferedReader br =
 new BufferedReader(new InputStreamReader
(System.in));
	BufferedReader br1 = 
 new BufferedReader(new InputStreamReader
(client.getInputStream()));

	PrintStream ps = new
PrintStream(client.getOutputStream());

	while(true)
	{
	msg = br1.readLine();
	System.out.println("Message is "+msg);
if(msg.equals("bye"))
	{
		break;
	}
	System.out.println("Enter Your Message");
	 smsg = br.readLine();
	ps.println(smsg);
	
	if(smsg.equals("bye"))
		{
			ps.println("bye");
			break;
		}
	}
	ps.close();
	br1.close();
	br.close();
	
	ss.close();
	
	}//try
	catch(Exception e)
	{
		System.out.println(e);
	}

}//main
}


/*CLient Program*/

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

public class chat_client
{

	public static void main(String[] args) 
	{
		Socket s;
		try
		{
		s = new Socket("127.0.0.1",1212);
		String msg,umsg;
		System.out.println("Clent is Conneccted
to the Server");
		
		BufferedReader br = new
BufferedReader(new InputStreamReader(System.in));
		BufferedReader br1 = new
BufferedReader(new InputStreamReader(s.getInputStream()));

		PrintStream ps = new PrintStream
(s.getOutputStream());
		while(true)
		{
		System.out.println("Enter Your
Message");
		msg = br.readLine();
		if(msg.equals("bye"))
			{
			break;
			}
		ps.println(msg);
		umsg = br1.readLine();
		System.out.println(umsg);
			
		if(umsg.equals("bye"))
		{
			ps.println("bye");
			break;
		}
		}	
		
	br1.close();
	ps.close();
	br.close();
	
	s.close();

	}
	catch(Exception e)
	{
		System.out.println(""+e);
	}//catch
	}//main
}

Label - java





by - Chinmay Mahajan





Are you looking for something else?


Suggested Programs




Difference between ArrayList and LinkedList in Java with example


AES Encryption and Decryption using Java


Dynamically Updating a List in JAVA


Upload and Preview Image using JFrame in Java


Connect Database and Retrieve values using JSP