在Java Socket中实现多线程通信,可以使用线程池来管理多个客户端连接。这里是一个简单的示例,展示了如何使用Java Socket和多线程实现服务器与多个客户端之间的通信。
- 首先,创建一个处理客户端请求的Runnable类:
import java.io.*; import java.net.Socket; public class ClientHandler implements Runnable { private final Socket clientSocket; public ClientHandler(Socket clientSocket) { this.clientSocket = clientSocket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true)) { String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("Received from client: " + inputLine); out.println("Server received: " + inputLine); } } catch (IOException e) { e.printStackTrace(); } finally { try { clientSocket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
- 然后,创建一个服务器类,用于监听客户端连接并将每个连接分配给一个新的线程:
import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; public class MultiThreadedServer { public static void main(String[] args) { int port = 8080; ExecutorService executorService = Executors.newFixedThreadPool(10); // 创建一个固定大小的线程池 try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("Server started on port: " + port); while (true) { Socket clientSocket = serverSocket.accept(); // 接受客户端连接 System.out.println("New client connected: " + clientSocket.getInetAddress()); ClientHandler clientHandler = new ClientHandler(clientSocket); executorService.submit(clientHandler); // 将客户端处理任务提交给线程池 } } catch (IOException e) { e.printStackTrace(); } finally { executorService.shutdown(); // 关闭线程池 } } }
- 最后,创建一个客户端类,用于与服务器进行通信:
import java.io.*; import java.net.Socket; public class Client { public static void main(String[] args) { String hostname = "localhost"; int port = 8080; try (Socket socket = new Socket(hostname, port); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) { System.out.println("Connected to server"); new Thread(() -> { try { String serverMsg; while ((serverMsg = in.readLine()) != null) { System.out.println("Server: " + serverMsg); } } catch (IOException e) { e.printStackTrace(); } }).start(); String userInput; while ((userInput = stdIn.readLine()) != null) { out.println(userInput); } } catch (IOException e) { e.printStackTrace(); } } }
现在,你可以运行服务器类和多个客户端类实例,它们将能够通过多线程通信。注意,这个示例仅用于演示目的,实际应用中需要考虑更多的错误处理和资源管理。