Java BIO 编程

2021-04-11  本文已影响0人  Cook1fan
image.png
image.png
image.png
public class BIOServer {
    public static void main(String[] args) throws IOException {
        // 线程池机制
        // 思路
        // 1 创建一个线程池
        // 2 如果有客户端连接,就创建一个线程,与之通讯(单独写一个方法)

        ExecutorService executorService = Executors.newCachedThreadPool();

        // 创建 ServerSocket
        ServerSocket serverSocket = new ServerSocket(6666);
        System.out.println("服务器启动");
        while (true) {
            // 监听,等待客户端连接
            System.out.println("线程ID = " + Thread.currentThread().getId() + ", 名称 = " + Thread.currentThread().getName());
            System.out.println("等待连接");
            final Socket socket = serverSocket.accept();
            System.out.println("连接到一个客户端");
            // 就创建一个线程,与之通讯(单独写一个方法)
            executorService.execute(() -> {
                // 可以和客户端通讯
                handler(socket);
            });
        }
    }

    // 编写一个 handler 方法,和客户端通讯
    public static void handler(Socket socket) {
        byte[] bytes = new byte[1024];
        try (socket) {
            System.out.println("线程ID = " + Thread.currentThread().getId() + ", 名称 = " + Thread.currentThread().getName());
            // 通过 socket 获取输入流
            InputStream inputStream = socket.getInputStream();
            // 循环的读取客户端发送的数据
            while (true) {
                System.out.println("线程ID = " + Thread.currentThread().getId() + ", 名称 = " + Thread.currentThread().getName());
                System.out.println("read...");
                int read = inputStream.read(bytes);
                if (read != -1) {
                    System.out.println(new String(bytes, 0, read)); // 输出客户端发送的数据
                } else {
                    break;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            System.out.println("关闭和client的连接");
        }
    }
    
}
image.png
上一篇 下一篇

猜你喜欢

热点阅读