Establishing the two-way Communication between Server and Client in Java

It is possible to send data from the server and receive a response from the client. Similarly, the client can also send and receive data to-and-from.

Below are the various steps to do so:

  • We need additional streams both at server and client. For example, to receive data into the server, it is a better idea to use a BufferedReader object, as shown in the following code snippet:
    InputStream obj = s.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(obj);
    
  • Then read() or readLine() methods of the BufferedReader object can be used to read data. To send data from the client we can take the help of the DataOutputStream class as shown in the following code snippet:
    OutputStream obj + s.getOutputStrean();
    DataOutputStream dos = new DataOutputStream(obj);
    
  • Then, the writeBytes() method of the DataOutputStream class can be used to send strings in the form of a group of bytes. To establish the two-way communication between a client and server perform the following steps:
    • Creating the Server Program: Let’s create a class named Server2.java to create server such that the server receives data from the client using a BufferedReader object and then sends a reply to the client using a PrintStream object.

      Server2.java

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Server2 class that
      // receives data and sends data
        
      import java.io.*;
      import java.net.*;
        
      class Server2 {
        
          public static void main(String args[])
              throws Exception
          {
        
              // Create server Socket
              ServerSocket ss = new ServerSocket(888);
        
              // connect it to client socket
              Socket s = ss.accept();
              System.out.println("Connection established");
        
              // to send data to the client
              PrintStream ps
                  = new PrintStream(s.getOutputStream());
        
              // to read data coming from the client
              BufferedReader br
                  = new BufferedReader(
                      new InputStreamReader(
                          s.getInputStream()));
        
              // to read data from the keyboard
              BufferedReader kb
                  = new BufferedReader(
                      new InputStreamReader(System.in));
        
              // server executes continuously
              while (true) {
        
                  String str, str1;
        
                  // repeat as long as the client
                  // does not send a null string
        
                  // read from client
                  while ((str = br.readLine()) != null) {
                      System.out.println(str);
                      str1 = kb.readLine();
        
                      // send to client
                      ps.println(str1);
                  }
        
                  // close connection
                  ps.close();
                  br.close();
                  kb.close();
                  ss.close();
                  s.close();
        
                  // terminate application
                  System.exit(0);
        
              } // end of while
          }
      }

      chevron_right

      
      

      Command to compile the Server2.Java file:



      D:\Conversation Program>javac Sever2.java
      
    • Creating the Client Program: Let’s create a client, named Client2.Java, which first connects to a server, then starts the communication by sending a string to the server. The server sends a response to the client. When ‘exit’ is typed at the client side, the program terminates.

      Client2.java

      filter_none

      edit
      close

      play_arrow

      link
      brightness_4
      code

      // Client2 class that
      // sends data and receives also
        
      import java.io.*;
      import java.net.*;
        
      class Client2 {
        
          public static void main(String args[])
              throws Exception
          {
        
              // Create client socket
              Socket s = new Socket("localhost", 888);
        
              // to send data to the server
              DataOutputStream dos
                  = new DataOutputStream(
                      s.getOutputStream());
        
              // to read data coming from the server
              BufferedReader br
                  = new BufferedReader(
                      new InputStreamReader(
                          s.getInputStream()));
        
              // to read data from the keyboard
              BufferedReader kb
                  = new BufferedReader(
                      new InputStreamReader(System.in));
              String str, str1;
        
              // repeat as long as exit
              // is not typed at client
              while (!(str = kb.readLine()).equals("exit")) {
        
                  // send to the server
                  dos.writeBytes(str + "\n");
        
                  // receive from the server
                  str1 = br.readLine();
        
                  System.out.println(str1);
              }
        
              // close connection.
              dos.close();
              br.close();
              kb.close();
              s.close();
          }
      }

      chevron_right

      
      

      Command to compile the Client2.java file:

      D:\Conversation Program>javac Client2.java
      
    • Output:
      To execute the Server2 and Client2 classes, run the Server2.java and Client2.java in two separate Command Prompt windows. Figure 1 shows the output of the Server2 and Client2 classes:

      Showing the Output of the Server2 and Client2 Classes



My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.