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

14 Oct, 2019
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);

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

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.javaServer2.java// 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    }}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.javaClient2.java// 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();    }}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
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.javaServer2.java// 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    }}Command to compile the Server2.Java file:D:\Conversation Program>javac Sever2.java

Server2.java
// 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    }}
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.javaClient2.java// 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();    }}Command to compile the Client2.java file:D:\Conversation Program>javac Client2.java

Client2.java
// 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();    }}
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
Showing the Output of the Server2 and Client2 Classes
Java-Networking
Java Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Iterate HashMap in Java?
Iterate Over the Characters of a String in Java
How to Get Elements By Index from HashSet in Java?
Java Program to Write into a File
How to Write Data into Excel Sheet using Java?
Java Program to Convert String to String Array
Modulo or Remainder Operator in Java
SHA-1 Hash
Comparing two ArrayList In Java
How to Replace a Element in Java ArrayList?