socket实现双向通信

GoogleVip8 1年前 ⋅ 808 阅读

服务端代码

int port = 55533;
int nThreads = 10;

ServerSocket serverSocket = new ServerSocket(port);
// demo 使用Executors创建线程池,正式是不推荐使用
ExecutorService executorService = Executors.newFixedThreadPool(nThreads);

// 循环获取socket通信
while (true) {
    Socket socket = serverSocket.accept();
    // 创建子线程处理socket通信
    executorService.submit(() -> {
        // 建立好连接后,从socket中获取输入流,并建立缓冲区进行读取
        try {
            // 建立好连接后,从socket中获取输入流,并建立缓冲区进行读取
            BufferedReader read = new BufferedReader(new InputStreamReader(socket.getInputStream(), "UTF-8"));
            String line;
            StringBuilder sb = new StringBuilder();
            while ((line = read.readLine()) != null) {
                //注意指定编码格式,发送方和接收方一定要统一,建议使用UTF-8
                sb.append(line);
            }
            System.out.println(sb);
						// 输出流,用于返回对象给客户端
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("回显".getBytes("UTF-8"));
            read.close();
            socket.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}

客户端代码

ExecutorService executorService = Executors.newFixedThreadPool(10);
for (int i = 0; i < 10; i++) {
    executorService.submit(()->{

        // 要连接的服务端IP地址和端口
        String host = "192.168.1.163";
        int port = 55533;
        // 与服务端建立连接
        Socket socket = null;
        try {
            socket = new Socket(host, port);
            // 建立连接后获得输出流
            OutputStream outputStream = socket.getOutputStream();
            String message="你好  socket";
            socket.getOutputStream().write(message.getBytes("UTF-8"));
            // 必需关闭输出流
            socket.shutdownOutput();
            // 获取输出流
            InputStream inputStream = socket.getInputStream();
            byte[] bytes = new byte[1024];
            int len;
            StringBuilder sb = new StringBuilder();
            while ((len = inputStream.read(bytes)) != -1) {
                //注意指定编码格式,发送方和接收方一定要统一,建议使用UTF-8
                sb.append(new String(bytes, 0, len,"UTF-8"));
            }
            System.out.println("get message from server: " + sb);

            inputStream.close();
            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    });
}
executorService.shutdown();

全部评论: 0

    我有话说: