Way2Java

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();
      }               
    }                    
}                        



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