在Java中,使用Socket通信實現多線程主要涉及到服務器端和客戶端的處理。下面分別介紹服務器端和客戶端如何實現多線程。
服務器端需要創建一個線程池來處理客戶端的連接請求。當客戶端連接到服務器時,服務器會創建一個新的線程來處理與該客戶端的通信。這樣可以確保服務器能夠同時處理多個客戶端的請求。
以下是一個簡單的服務器端多線程實現示例:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Server {
public static void main(String[] args) throws IOException, InterruptedException {
int port = 12345;
ExecutorService executorService = Executors.newFixedThreadPool(10); // 創建一個固定大小的線程池
try (ServerSocket serverSocket = new ServerSocket(port)) {
System.out.println("Server is listening on port " + port);
while (true) {
try (Socket socket = serverSocket.accept()) {
executorService.submit(() -> handleClient(socket)); // 將客戶端連接請求提交給線程池處理
} catch (IOException e) {
System.out.println("Error accepting client connection: " + e.getMessage());
}
}
} finally {
executorService.shutdown(); // 關閉線程池
}
}
private static void handleClient(Socket socket) {
try {
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received from client: " + message);
// 處理客戶端發送的消息
}
} catch (IOException e) {
System.out.println("Error handling client communication: " + e.getMessage());
} finally {
try {
socket.close();
} catch (IOException e) {
System.out.println("Error closing client socket: " + e.getMessage());
}
}
}
}
客戶端也可以使用多線程來實現多個連接的并發處理。例如,可以創建一個線程池,并為每個需要連接的服務器端端口分配一個線程。
以下是一個簡單的客戶端多線程實現示例:
import java.io.*;
import java.net.*;
import java.util.concurrent.*;
public class Client {
public static void main(String[] args) throws IOException, InterruptedException {
String serverAddress = "localhost";
int serverPort = 12345;
int numberOfConnections = 5; // 需要連接的服務器端端口數量
ExecutorService executorService = Executors.newFixedThreadPool(numberOfConnections); // 創建一個固定大小的線程池
for (int i = 0; i < numberOfConnections; i++) {
executorService.submit(() -> connectToServer(serverAddress, serverPort)); // 將連接請求提交給線程池處理
}
executorService.shutdown(); // 關閉線程池
}
private static void connectToServer(String serverAddress, int serverPort) throws IOException {
try (Socket socket = new Socket(serverAddress, serverPort);
InputStream inputStream = socket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream))) {
String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received from server: " + message);
// 處理服務器發送的消息
}
} catch (IOException e) {
System.out.println("Error connecting to server: " + e.getMessage());
}
}
}
這個示例中,客戶端創建了5個線程,每個線程都嘗試連接到服務器。服務器端使用線程池處理客戶端的連接請求。這樣,客戶端和服務器端都可以實現多線程通信。