Untitled
unknown
plain_text
4 months ago
1.8 kB
3
Indexable
import java.net.*; import java.io.*; public class MultiThreadServer { public static void main(String[] args) throws IOException { try (ServerSocket serverSocket = new ServerSocket(12345)) { System.out.println("服务器已启动,监听端口:12345"); while (true) { Socket clientSocket = serverSocket.accept(); new ClientHandler(clientSocket).start(); } } } private static class ClientHandler extends Thread { private final Socket socket; public ClientHandler(Socket socket) { this.socket = socket; } public void run() { try (BufferedReader in = new BufferedReader( new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter( socket.getOutputStream(), true)) { String clientIP = socket.getInetAddress().getHostAddress(); System.out.println("客户端[" + clientIP + "]已连接"); String inputLine; while ((inputLine = in.readLine()) != null) { System.out.println("收到消息:" + inputLine); // 业务处理逻辑 String response = "服务器响应:" + inputLine.toUpperCase(); out.println(response); } } catch (IOException e) { System.err.println("连接异常:" + e.getMessage()); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
Editor is loading...
Leave a Comment