在Java中,使用Socket結合多線程可以實現客戶端和服務器之間的多線程通信。下面是一個簡單的示例,展示了如何使用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); // 創建一個固定大小的線程池
ServerSocket serverSocket = new ServerSocket(port);
System.out.println("Server is listening on port " + port);
while (true) {
Socket clientSocket = serverSocket.accept();
executorService.execute(new ClientHandler(clientSocket)); // 將客戶端連接交給線程池處理
}
}
}
class ClientHandler implements Runnable {
private Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try {
InputStream inputStream = clientSocket.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
String message;
while ((message = reader.readLine()) != null) {
System.out.println("Received from client: " + message);
// 發送響應給客戶端
OutputStream outputStream = clientSocket.getOutputStream();
PrintWriter writer = new PrintWriter(outputStream, true);
writer.println("Server response: " + message);
}
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客戶端代碼:
import java.io.*;
import java.net.*;
public class Client {
public static void main(String[] args) throws IOException {
String serverAddress = "localhost";
int port = 12345;
Socket socket = new Socket(serverAddress, port);
System.out.println("Connected to server");
BufferedReader reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
PrintWriter writer = new PrintWriter(socket.getOutputStream(), true);
// 發送消息給服務器
writer.println("Hello, Server!");
System.out.println("Sent message to server");
// 讀取服務器的響應
String response = reader.readLine();
System.out.println("Received from server: " + response);
socket.close();
}
}
在這個示例中,服務器使用了一個固定大小的線程池來處理客戶端連接。當服務器接收到一個新的客戶端連接時,它會將這個連接交給線程池中的一個線程來處理。這樣可以確保服務器能夠同時處理多個客戶端連接,而不會因為處理單個連接而阻塞其他連接。
客戶端通過Socket連接到服務器,并發送一條消息給服務器。服務器接收到消息后,會將其原樣返回給客戶端。客戶端在接收到服務器的響應后,關閉與服務器的連接。