今天继续学习网络编程
多线程服务器
在实际应用中,服务器通常需要同时处理多个客户端连接。多线程服务器可以通过为每个客户端连接创建一个新线程来实现。例如:
java
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
public class MultiThreadedServer {
public static void main(String[] args) {
try (ServerSocket serverSocket = new ServerSocket(12345)) {
System.out.println("Server is listening on port 12345");
while (true) {
Socket clientSocket = serverSocket.accept();
System.out.println("New client connected");
Thread thread = new ClientHandler(clientSocket);
thread.start();
}
} catch (IOException e) {
e.printStackTrace();
}
}
static class ClientHandler extends Thread {
private final Socket clientSocket;
public ClientHandler(Socket socket) {
this.clientSocket = socket;
}
@Override
public void run() {
try (PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()))) {
String request = in.readLine();
System.out.println("Client request: " + request);
out.println("Hello, Client!");
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
clientSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
在这个例子中,服务器为每个客户端连接创建一个ClientHandler线程,处理客户端请求并发送响应。
通过今天的学习,我对Java网络编程有了较为深入的了解。