欢迎您访问365答案网,请分享给你的朋友!
生活常识 学习资料

可重复连接的Socket服务端与客户端

时间:2023-06-07

可支持多客户端的服务器:

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(); }}

Copyright © 2016-2020 www.365daan.com All Rights Reserved. 365答案网 版权所有 备案号:

部分内容来自互联网,版权归原作者所有,如有冒犯请联系我们,我们将在三个工作时内妥善处理。