在Java中,可以通過多線程來實現Socket通信。下面是一個簡單的示例代碼,演示了如何使用多線程實現Socket通信:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiThreadedServer {
public static void main(String[] args) {
ServerSocket serverSocket = null;
try {
serverSocket = new ServerSocket(12345);
System.out.println("Server started. Listening for connections on port 12345...");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("Connection received from " + clientSocket.getInetAddress().getHostAddress());
ClientHandler clientHandler = new ClientHandler(clientSocket);
Thread clientThread = new Thread(clientHandler);
clientThread.start();
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (serverSocket != null) {
try {
serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
static class ClientHandler implements Runnable {
private 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();
}
}
}
}
在這個示例中,ServerSocket在端口12345上監聽客戶端連接。一旦有連接建立,就會創建一個新的ClientHandler線程來處理該連接。ClientHandler類實現了Runnable接口,用于處理客戶端的輸入和輸出。
在ClientHandler線程中,我們創建了一個BufferedReader來讀取客戶端發送的消息,并通過PrintWriter來向客戶端發送消息。循環讀取客戶端發送的消息,直到客戶端關閉連接。
這樣,通過多線程的方式,我們可以實現Socket通信,并同時處理多個客戶端的連接。