在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连接到服务器,并发送一条消息给服务器。服务器接收到消息后,会将其原样返回给客户端。客户端在接收到服务器的响应后,关闭与服务器的连接。