Chat Program two way communication Java

Chat Program Java is a continuous communication between two systems. Networking chapter also (apart threads, DS etc.) proves that Java language is simple to develop applications that are difficult (requires extra practice and experience) in other languages.

Before going into the details of client-server communication, it is advised to go through Networking – Introduction and Communication with TCP/IP Protocol to know the terms and basics of networking and the way Java supports.

Total 4 programs are given in TCP/IP protocol based communication.

Application Number Functionality
1st application Client to server communication (one-way)
2nd application Server to client communication (one-way)
3rd application Server sends file contents to client (two-way, non-continuous)
4th application Chat program (two-way, continuous)

4th application – Chat Program Java: Chat communication (two-way continuous)

This is the last one of the four series where client and server talks continuously until one disconnets.

Chat communication is the process of exchanging messages between two systems continuously. Anyone can break the communication. Both systems come with the following same responsibilities.

  1. Reading from keyboard. Uses an input stream like BufferedReader connected to System.in.
  2. Sending data to the other system what is read from keyboard. Uses an output stream like PrintWriter connected to getOutputStream() method of Socket.
  3. Receiving data from the other system. Uses an input stream like BufferedReader connected to getInputStream() method of Socket.

As the responsibilities are same, both client and server programs contain the same stream objects and same code. The order of using stream objects varies in the while loop.

Client program: GossipClient.java

import java.io.*;
import java.net.*;
public class GossipClient
{
  public static void main(String[] args) throws Exception
  {
     Socket sock = new Socket("127.0.0.1", 3000);
                               // reading from keyboard (keyRead object)
     BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
                              // sending to client (pwrite object)
     OutputStream ostream = sock.getOutputStream(); 
     PrintWriter pwrite = new PrintWriter(ostream, true);

                              // receiving from server ( receiveRead  object)
     InputStream istream = sock.getInputStream();
     BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

     System.out.println("Start the chitchat, type and press Enter key");

     String receiveMessage, sendMessage;               
     while(true)
     {
        sendMessage = keyRead.readLine();  // keyboard reading
        pwrite.println(sendMessage);       // sending to server
        pwrite.flush();                    // flush the data
        if((receiveMessage = receiveRead.readLine()) != null) //receive from server
        {
            System.out.println(receiveMessage); // displaying at DOS prompt
        }         
      }               
    }                    
}                        

Note: To come out of the chat, type Ctrl+C.

Server program: GossipServer.java

import java.io.*;
import java.net.*;
public class GossipServer
{
  public static void main(String[] args) throws Exception
  {
      ServerSocket sersock = new ServerSocket(3000);
      System.out.println("Server  ready for chatting");
      Socket sock = sersock.accept( );                          
                              // reading from keyboard (keyRead object)
      BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
	                      // sending to client (pwrite object)
      OutputStream ostream = sock.getOutputStream(); 
      PrintWriter pwrite = new PrintWriter(ostream, true);

                              // receiving from server ( receiveRead  object)
      InputStream istream = sock.getInputStream();
      BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

      String receiveMessage, sendMessage;               
      while(true)
      {
        if((receiveMessage = receiveRead.readLine()) != null)  
        {
           System.out.println(receiveMessage);         
        }         
        sendMessage = keyRead.readLine(); 
        pwrite.println(sendMessage);             
        pwrite.flush();
      }               
    }                    
}                        


Chat Program Java
Screenshot on Chat Program Java

pwrite.flush();

The flush() method of PrintStream class flushes any uncleared buffers in memory. Generally when the streams are closed, the buffers are pushed out of all the data contained in. But, in the program no stream is closed; so, it is necessary to flush the data explicitly with flush() method.

As you can observe, both programs are using same streams and objects. The difference comes in while loop. Client sends first and then receives where as server first receives and then sends. The other terms of the code are explained in the earlier three applications.

Do you know?

1. A frame can be created without a border.
2. Coffee cup on the frame title bar can be changed with your photo.
3. Size of the button depends on the layout manager you choose.
4. The space along the border of the frame and components inside can be adjusted.
5. Java support freelance drawing using AWT.
6. Components can be added without using layout manager.
7. Dialog box can be modal or modeless.
8. There exists HeadlessException in AWT.
9. You can draw a cube, cylinder etc. without having predefined methods.
10. addActionListener() is a method of Button but not ActionListener.
11. Importing both java.awt and java.awt.event

45 thoughts on “Chat Program two way communication Java”

  1. Annavarapu.Mani Meghana

    sir i need implmention chat server with scoket application plz help out program should be in python language.

  2. Sir,
    if we run server program in one machine and client program in another program where computer are connected in LAN.
    than this program works or it needs any modification.

  3. //MultiClient-Server

    //MServer

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

    class MServer implements Runnable
    {
    ServerSocket ss;

    public void run()
    {
    String name = Thread.currentThread().getName();
    while(true)
    {
    try{
    System.out.println(“Client “+name+” ready to accept…”);
    Socket s = ss.accept();
    System.out.println(“Client “+name+” accepted the connection”);
    BufferedReader readKb = new BufferedReader(new InputStreamReader(System.in));
    PrintStream writeC = new PrintStream(s.getOutputStream(), true);
    BufferedReader readC = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String msgFromC, msgToC;
    while(true)
    {
    if((msgFromC = readC.readLine()) != null)
    System.out.print(“\nClient “+name+” : “+msgFromC+”\n\nYou : “);
    msgToC = readKb.readLine();
    writeC.println(msgToC);
    writeC.flush();
    }
    }
    catch(Exception e) { }
    }
    }

    public static void main(String[] args)
    {
    try {
    MServer ms = new MServer();
    ss = new ServerSocket(156);

    Thread t1 = new Thread(ms, “One”);
    Thread t2 = new Thread(ms, “Two”);
    t1.start();
    t2.start();
    }catch(Exception e) { }
    }
    }

    //MClient

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

    class MClient
    {
    public static void main(String[] args)
    {
    try {
    Socket s = new Socket(“localhost”, 156);
    BufferedReader readKb = new BufferedReader(new InputStreamReader(System.in));
    PrintStream writeS = new PrintStream(s.getOutputStream(), true);
    BufferedReader readS = new BufferedReader(new InputStreamReader(s.getInputStream()));
    System.out.println(“You may begin chatting :\n”);
    String msgFromS, msgToS;
    while(true)
    {
    msgToS = readKb.readLine();
    writeS.println(msgToS);
    writeS.flush();
    if((msgFromS = readS.readLine()) != null)
    System.out.print(“\nServer : “+msgFromS+”\n\nYou : “);
    }
    }catch(Exception e) {}
    }
    }

  4. Hello sir,
    When i run this programs in two command prompts i didnt get messages in server, whatever i typed in client console. how to run this properly
    R.Vithu

    1. First run always server program from one prompt. Then type from other DOS prompt the client program. First conversation should be started by client, then server, then client like this. Do not type two times and press enter at a single DOS prompt. Then you have to close the prompt and restart again.

  5. Dear sir,
    When I am trying the program in local host I am unable to send multiple messages till I get reply from server. Please can say me the program to communicate without interruption.
    both of them should receive messages without any reply also.

  6. This is a program for server that can talk with multiple client :
    /*
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    */
    package ChatApp;

    import java.io.*;
    import java.net.*;
    public class ChatServer implements Runnable
    {
    Socket sock;

    int ID;
    public static void main(String[] args) throws Exception
    {
    int count=0;
    try{
    ServerSocket sersock = new ServerSocket(19999);
    System.out.println(“Server ready for chatting”);
    while (true) {
    Socket sock = sersock.accept();
    Runnable runnable = new ChatServer(sock,++count);
    Thread thread = new Thread(runnable);
    thread.start();
    }
    }
    catch(Exception e){}

    }
    ChatServer(Socket s, int i) {
    this.sock = s;
    this.ID = i;
    }

    @Override
    public void run() {
    try{
    BufferedReader keyRead = new BufferedReader(new InputStreamReader(System.in));
    // sending to client (pwrite object)
    OutputStream ostream = sock.getOutputStream();
    PrintWriter pwrite = new PrintWriter(ostream, true);

    // receiving from server ( receiveRead object)
    InputStream istream = sock.getInputStream();
    BufferedReader receiveRead = new BufferedReader(new InputStreamReader(istream));

    String receiveMessage, sendMessage;
    while(true)
    {
    if((receiveMessage = receiveRead.readLine()) != null)
    {
    System.out.println(receiveMessage);
    }
    sendMessage = keyRead.readLine();
    pwrite.println(sendMessage);
    pwrite.flush();
    }
    }
    catch(IOException e1)
    {
    System.out.println(e1);
    }
    catch(Exception e2)
    {
    System.out.println(e2);
    }
    }
    }
    and for client side code remain same…have fun…

  7. if we uses BufferReader and BufferWriter in client as well as server side(for 2 way connection BUT 1 RESPONSE FROM BOTH) y it dont work becoz both are high stream and high stream can go to high stream
    and one more problm which i saw that if you put buffer reader in server side and buffer writer in the client side then it show null value in the server and show socket close problm in the client side y this happen u can even check the below codes
    please answer

    for server

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

    public class Server {
    public static void main(String[] args) throws Exception {

    System.out.print(“Server started”);
    ServerSocket ss= new ServerSocket(5000);
    Socket so=ss.accept();
    System.out.println(“client connected”);

    DataOutputStream dos=new DataOutputStream(so.getOutputStream());

    BufferedReader din= new BufferedReader(new InputStreamReader(so.getInputStream()));

    BufferedReader b1= new BufferedReader(new InputStreamReader(System.in));

    System.out.println(“Entr msg”);
    String str=b1.readLine();
    dos.writeUTF(str);
    System.out.println(“your msg” + din.readLine());
    dos.close();
    din.close();
    b1.close();
    }
    }

    for client

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

    class Client
    {
    public static void main(String…aa) throws Exception
    {
    InetAddress inet= InetAddress.getLocalHost();
    Socket so= new Socket(inet,5000);

    DataInputStream din=new DataInputStream(so.getInputStream());

    BufferedWriter dos =new BufferedWriter(new OutputStreamWriter(so.getOutputStream()));

    BufferedReader b1= new BufferedReader(new InputStreamReader(System.in));

    System.out.println(“Entr msg”);
    String str=b1.readLine();
    dos.write(str);
    System.out.println(“your msg” + din.readUTF());
    din.close();
    dos.close();
    b1.close();
    }

    }

  8. i am trying only one response from both i.e. client and server but the code for server of mine is not working can you help me whats the problm with the code

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

    class server
    {
    public static void main(String…aa) throws Exception
    {
    InetAddress inet= InetAddress.getLocalHost();
    ServerSocket ss= new ServerSocket(5000);
    Socket so=ss.accept();

    BufferedReader br= new BufferedReader(new InputStreamReader(System.in));

    OutputStream os=so.getOutputStream();
    BufferedWriter bw= new BufferedWriter(new OutputStreamWriter(os));

    InputStream is=so.getInputStream();
    BufferedReader br1= new BufferedReader(new InputStreamReader(is));

    String str=br.readLine();

    bw.write(str);
    bw.flush();
    System.out.println( br1.readLine());

    }

    }

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

        class client
        {
        public static void main(String…aa) throws Exception
        {
        InetAddress inet= InetAddress.getLocalHost();
        Socket so= new Socket(inet,5000);

        BufferedReader bw= new BufferedReader(new InputStreamReader(System.in));

        OutputStream is1=so.getOutputStream();
        PrintWriter bw1= new PrintWriter(is1,true);

        InputStream is=so.getInputStream();
        BufferedReader br= new BufferedReader(new InputStreamReader(is));

        System.out.println(br.readLine());
        String str=bw.readLine();
        bw1.println(str);
        System.out.flush();

        }

        }

  9. the same ques is mine too is it possible to connect to many clients and if yes then how becoz here server and one client is in communication untill connection will not b cutted next client cant make connection

Leave a Comment

Your email address will not be published.