📌  相关文章
📜  在Java中建立服务器和客户端之间的双向通信

📅  最后修改于: 2022-05-13 01:58:09.299000             🧑  作者: Mango

在Java中建立服务器和客户端之间的双向通信

可以从服务器发送数据并从客户端接收响应。同样,客户端也可以相互发送和接收数据。

以下是执行此操作的各个步骤:

  • 我们在服务器和客户端都需要额外的流。例如,要将数据接收到服务器,最好使用 BufferedReader 对象,如以下代码片段所示:
    InputStream obj = s.getInputStream();
    BufferedReader br = new BufferedReader(new InputStreamReader(obj);
    
  • 然后可以使用 BufferedReader 对象的 read() 或 readLine() 方法来读取数据。要从客户端发送数据,我们可以借助 DataOutputStream 类,如以下代码片段所示:
    OutputStream obj + s.getOutputStrean();
    DataOutputStream dos = new DataOutputStream(obj);
    
  • 然后,可以使用DataOutputStream类的writeBytes()方法以一组字节的形式发送字符串。要在客户端和服务器之间建立双向通信,请执行以下步骤:
    • 创建服务器程序:让我们创建一个名为Server2 的类。 Java创建服务器,以便服务器使用 BufferedReader 对象从客户端接收数据,然后使用 PrintStream 对象向客户端发送回复。
      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
          }
      }


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


      编译Server2的命令。 Java文件

      D:\Conversation Program>javac Sever2.java
      
    • 创建客户端程序:让我们创建一个名为Client2 的客户端。 Java首先连接到服务器,然后通过向服务器发送字符串来开始通信。服务器向客户端发送响应。当在客户端输入“exit”时,程序终止。

      客户2。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();
          }
      }
      

      编译Client2的命令。 Java文件:

      D:\Conversation Program>javac Client2.java
      
    • 输出:
      要执行Server2Client2类,请运行Server2。 JavaClient2。 Java在两个单独的命令提示符窗口中。图 1 显示了 Server2 和 Client2 类的输出:

      显示 Server2 和 Client2 类的输出