Home  >  Article  >  Java  >  How to perform multi-threaded communication in Java network programming?

How to perform multi-threaded communication in Java network programming?

王林
王林Original
2024-04-15 22:03:02305browse

Multi-threaded communication in Java network programming allows multiple clients or servers to connect to the same application simultaneously, improving efficiency and responding to requests. Implementing multi-threaded communication requires the use of ServerSocket and Socket classes by creating ServerSocket objects to listen for incoming connections and creating separate threads for each connection to process data, such as receiving and sending responses. For example, in the actual case, the echo server will return the received message to the client as it is, demonstrating the application of multi-threaded communication in network programming.

How to perform multi-threaded communication in Java network programming?

Multi-threaded communication in Java network programming

In Java network programming, multi-threaded communication allows multiple clients or Servers connect to the same application simultaneously, increasing efficiency and responding to more requests.

Achieving multi-threaded communication

To achieve multi-threaded communication, you can use the ServerSocket and Socket classes:

  1. Create a ServerSocket object to listen for incoming connections:

    ServerSocket serverSocket = new ServerSocket(port);
  2. Create a separate thread to handle each incoming connection The connection:

    while (true) {
      Socket socket = serverSocket.accept();
      Runnable task = new ClientHandler(socket);  // ClientHandler 为处理连接的自定义类
      new Thread(task).start();
    }
  3. In the ClientHandler class, handle the data received from the socket and send the response:

    class ClientHandler implements Runnable {
    
      private Socket socket;
    
      public ClientHandler(Socket socket) {
     this.socket = socket;
      }
    
      @Override
      public void run() {
     // 从套接字接收数据
     BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
     String request = in.readLine();
    
     // 准备并发送响应
     String response = "HTTP/1.1 200 OK\n";
     socket.getOutputStream().write(response.getBytes());
    
     // 关闭套接字
     socket.close();
      }
    }

Practical Case: Echo Server

This is a simple example of an echo server that will return any message it receives to the client unchanged:

Server

import java.net.ServerSocket;
import java.net.Socket;

public class EchoServer {

  public static void main(String[] args) throws Exception {
    // 监听端口 8080 的传入连接
    ServerSocket serverSocket = new ServerSocket(8080);

    while (true) {
      // 接受传入的连接
      Socket socket = serverSocket.accept();

      // 处理连接的线程
      Runnable task = new ClientHandler(socket);
      new Thread(task).start();
    }
  }

  private static class ClientHandler implements Runnable {

    private Socket socket;

    public ClientHandler(Socket socket) {
      this.socket = socket;
    }

    @Override
    public void run() {
      try {
        // 从客户端接收消息
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
        String message = in.readLine();

        // 将消息原样返回给客户端
        socket.getOutputStream().write((message + "\n").getBytes());

        // 关闭连接
        socket.close();
      } catch (Exception e) {
        e.printStackTrace();
      }
    }
  }
}

Client

import java.net.Socket;

public class EchoClient {

  public static void main(String[] args) throws Exception {
    // 连接到回声服务器的 8080 端口
    Socket socket = new Socket("localhost", 8080);

    // 向服务器发送消息
    socket.getOutputStream().write("Hello world!\n".getBytes());

    // 从服务器接收响应
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    String response = in.readLine();

    // 打印服务器的响应
    System.out.println("Server response: " + response);

    // 关闭连接
    socket.close();
  }
}

The above is the detailed content of How to perform multi-threaded communication in Java network programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn