Chat Application Version 1

Chat server for providing chatting between client and server

In this post we will learn how to develop an initial version of chat application in java. For chat application both program need to have input from user and send it to another party.

Chat server Program

This server first wait for client request and then it will take input from user and send it to client and at last print message coming from client on screen. These operation except waiting for client's request will be run in a loop.

Tcp socket server program


import java.net.*;
import java.io.*;
class chat1
 {
   public static void main(String arg[]) throws IOException
     {
	   ServerSocket server=new ServerSocket(5000);
	   BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	   BufferedReader in;
	   PrintWriter out;
	   Socket  s;
	   String message;
	   while(true)
	    {
	   System.out.println("Waiting ....");
	  	  
	s=server.accept();
		
		 
	   System.out.println("Connection Established!!");
	   out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
	   in=new BufferedReader(new InputStreamReader(s.getInputStream()));
	  while(true)
       {
     	   
	   // Take Input from User
	   message=br.readLine(); 
	   
	   // Send user input to Client
	   out.println(message);
	   out.flush();
	   
	   // Receive message from client on screen
	   
	   System.out.println("Client:"+in.readLine());
	   
	  }
	   
	  }
	 }
 }
   


Chat client program

Client program first connect to server application, then it receive message from server. Then it will take input from user and send it to server.

import java.io.*;
import java.net.*;
class chat2
 {
   public static void main(String arg[]) throws IOException
     {
	  BufferedReader br;
	  BufferedReader in;
	  PrintWriter out;
	  String message;
	  Socket s;
	  s=new Socket("127.0.0.1",5000);
	     System.out.println("Connection established!!");
	   br=new BufferedReader(new InputStreamReader(System.in)); 
	   
	   in=new BufferedReader(new InputStreamReader(s.getInputStream()));
	   out=new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
	    while(true)
		 {
		   System.out.println("Server:"+in.readLine());
		   message=br.readLine();
		   out.println(message);
		   out.flush();
		 }
	   
	   
	 }
 }
   

Execution of Programs

compile both program by using following commands on command interpreter


c:>javac server.java
c:>javac client.java

Run server program first then open another command prompt and run client program in that command prompt

c:>java server
Waiting...

On execution of client program

c:>java client
Connection established!!

After execution write some message in server program then write message in client program.

Limitaton! This applicaton has one limitation that this is one way communication. It means that first server send message then client send.

Two Way Chatting Application with multithreading