在Java Socket中實現多線程通信,可以使用線程池來管理多個客戶端連接。這里是一個簡單的示例,展示了如何使用Java Socket和多線程實現服務器與多個客戶端之間的通信。
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();
}
}
}
現在,你可以運行服務器類和多個客戶端類實例,它們將能夠通過多線程通信。注意,這個示例僅用于演示目的,實際應用中需要考慮更多的錯誤處理和資源管理。