可支持多客户端的服务器:
1、当有新连接加入,使用线程池处理连接。
2、已有连接可重复接收到消息。
public static void main(String[] args) { // 创建一个线程池,如果有客户端连接就创建一个线程与之通信 ExecutorService executorService = Executors.newCachedThreadPool(); try (ServerSocket serverSocket = new ServerSocket(9999)) { while (true) { final Socket socket = serverSocket.accept(); System.out.println("connection..."); executorService.execute(() -> handle(socket)); } } catch (IOException e) { e.printStackTrace(); }}private static void handle(Socket socket) { System.out.println("id = " + Thread.currentThread().getId()); while (!socket.isClosed()) { try { InputStream inputStream = socket.getInputStream(); byte[] read = new byte[1024]; int len = inputStream.read(read); String msg = new String(read, 0, len); if ("exit".equals(msg)) { socket.close(); break; } System.out.println("客户端消息:" + msg); socket.getOutputStream() .write(("read msg:"+msg).getBytes(StandardCharsets.UTF_8)); } catch (IOException e) { System.out.println("......"); try { socket.close(); } catch (IOException ex) { ex.printStackTrace(); } } } if (socket.isClosed()) { System.out.println("connection closed."); }}
可重复发送消息的客户端:
public static void main(String[] args) { try (Socket socket = new Socket("127.0.0.1", 9999)){ while (true) { System.out.print("请输入:"); Scanner scanner = new Scanner(System.in); String line = scanner.nextLine(); socket.getOutputStream() .write(line.getBytes(StandardCharsets.UTF_8)); if ("exit".equals(line)) { socket.close(); break; } byte[] read = new byte[1024]; int len = socket.getInputStream().read(read); System.out.println(new String(read, 0, len)); } } catch (IOException e) { e.printStackTrace(); }}