标签:java,socket,知识,System,String,println,new,多线程,out From: https://blog.csdn.net/laocooon/article/details/142739463服务器:
package p1007; import java.io.*; import java.net.*; import java.util.Random; public class Server { public static void main(String[] args) { int port = 12345; // 服务端口 try (ServerSocket serverSocket = new ServerSocket(port)) { System.out.println("服务器已启动,等待客户端连接..."); while (true) { Socket socket = serverSocket.accept(); System.out.println("客户端连接: " + socket.getInetAddress()); new ClientHandler(socket).start(); // 为每个客户端连接启动一个新线程 } } catch (IOException e) { e.printStackTrace(); } } } class ClientHandler extends Thread { private Socket socket; public ClientHandler(Socket socket) { this.socket = socket; } @Override public void run() { try (BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true)) { Random random = new Random(); int num1 = random.nextInt(100); int num2 = random.nextInt(100); int correctAnswer = num1 + num2; out.println("请计算: " + num1 + " + " + num2 + " = ?"); String inputLine; while ((inputLine = in.readLine()) != null) { try { int userAnswer = Integer.parseInt(inputLine); if (userAnswer == correctAnswer) { out.println("回答正确!连接结束。"); System.out.println(socket.getInetAddress()+"回答正确!连接结束。"); out.println("结束"); System.out.println(socket.getInetAddress()+"结束"); break; } else { System.out.println(socket.getInetAddress()+"错误,请再试一次:"); out.println("错误,请再试一次:"); } } catch (NumberFormatException e) { out.println("无效输入,请输入一个数字。"); System.out.println(socket.getInetAddress()+"无效输入,请输入一个数字。"); } } } catch (IOException e) { e.printStackTrace(); } finally { try { socket.close(); } catch (IOException e) { e.printStackTrace(); } } } }
客服机:
package p1007; import java.io.*; import java.net.*; public class Client { public static void main(String[] args) { String serverAddress = "localhost"; // 服务器地址 int port = 12345; // 服务器端口 try (Socket socket = new Socket(serverAddress, port); BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream())); PrintWriter out = new PrintWriter(socket.getOutputStream(), true); BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in))) { String serverMessage; while ((serverMessage = in.readLine()) != null) { System.out.println("服务器: " + serverMessage); if(serverMessage.equals("回答正确!连接结束。")) break; System.out.print("您的答案: "); String answer = userInput.readLine(); out.println(answer); // 发送用户的答案 } } catch (IOException e) { e.printStackTrace(); } System.out.println("结束"); } }