Java NIO - 群聊

LZC發表於2020-06-16
public class NIOServer {
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    private static final int PORT = 1212;
    public NIOServer() throws IOException {
        // 先用open方法建立一個物件
        serverSocketChannel = ServerSocketChannel.open();
        // 繫結埠
        serverSocketChannel.bind(new InetSocketAddress("localhost",PORT));
        serverSocketChannel.configureBlocking(false);
        // 建立一個Selector
        selector = Selector.open();
        // 把一個Channel註冊到Selector
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    }

    public void listen() throws IOException {
        while (true) {
            // 阻塞在 select
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 遍歷selectKeys
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey key = iterator.next();
                if (key.isAcceptable()) {
                    // accept事件
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("accept new conn: " + socketChannel.getRemoteAddress());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    // 讀取事件
                    readData(key);
                }
                iterator.remove();
            }
        }
    }

    private void readData(SelectionKey key) throws IOException {
        SocketChannel socketChannel = (SocketChannel) key.channel();
        // ByteBuffer buffer = ByteBuffer.allocateDirect(1024); 直接記憶體
        ByteBuffer buffer = ByteBuffer.allocate(1024); // 記憶體
        // 將資料讀入到buffer中
        int readBytes = 0; //
        try {
            readBytes = socketChannel.read(buffer);
            if (readBytes > 0) {
                buffer.flip();
                // buffer.remaining()返回的是需要讀多少位元組
                byte[] bytes = new byte[buffer.remaining()];
                // 將資料寫入到byte陣列中
                buffer.get(bytes);
                String body = new String(bytes, StandardCharsets.UTF_8);
                // 將訊息分發給所有人
                sendMessageToAll(socketChannel.getRemoteAddress() + "==>" + body, socketChannel);
                if ("quit".equals(body)) {
                    //取消註冊
                    key.cancel();
                    //關閉通道
                    socketChannel.close();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void sendMessageToAll(String body, SocketChannel self) throws IOException {
        System.out.println(body);
        for (SelectionKey key : selector.keys()) {
            Channel targetChannel = key.channel();

            // 不傳送給自己
            if (targetChannel instanceof SocketChannel && targetChannel != self) {
                SocketChannel dest = (SocketChannel)targetChannel;

                ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
                buffer.put(body.getBytes(StandardCharsets.UTF_8));
                buffer.flip();

                dest.write(buffer);
            }
        }
    }

    public static void main(String[] args) throws IOException {
        new NIOServer().listen();
    }
}
public class NIOClient {

    private SocketChannel socketChannel;

    private volatile boolean isClosed = false;

    public NIOClient() throws IOException {
        socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost",1212));
    }

    public void start() {
        // 啟動一個執行緒用來監聽接收訊息
        new Thread(()->{
            try {
                // 建立一個Selector
                Selector selector = Selector.open();
                socketChannel.configureBlocking(false);
                // 把一個Channel註冊到Selector
                socketChannel.register(selector, SelectionKey.OP_READ);
                while (!isClosed) {
                    // 阻塞在 select
                    selector.select();
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    // 遍歷selectKeys
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();

                    while (iterator.hasNext()) {
                        SelectionKey key = iterator.next();
                        if (key.isReadable()) {
                            // 讀取事件
                            SocketChannel sc = (SocketChannel) key.channel();
                            // ByteBuffer buffer = ByteBuffer.allocateDirect(1024); 直接記憶體
                            ByteBuffer buffer = ByteBuffer.allocate(1024); // 記憶體
                            // 將資料讀入到buffer中
                            int readBytes = sc.read(buffer); //
                            if (readBytes > 0) {
                                buffer.flip();
                                // buffer.remaining()返回的是需要讀多少位元組
                                byte[] bytes = new byte[buffer.remaining()];
                                // 將資料寫入到byte陣列中
                                buffer.get(bytes);
                                String body = new String(bytes, StandardCharsets.UTF_8);
                                System.out.println(body);
                            }
                        }
                        iterator.remove();
                    }
                }
                socketChannel.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }).start();

        // 開啟一個執行緒來傳送訊息
        new Thread(()->{
            // 主執行緒用來傳送訊息
            Scanner sc = new Scanner(System.in);

            while (true) {
                String msg = sc.next();
                ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
                buffer.put(msg.getBytes(StandardCharsets.UTF_8));
                buffer.flip();
                try {
                    socketChannel.write(buffer);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                if ("quit".equals(msg)) {
                    this.isClosed = true;
                    break;
                }
            }
        }).start();
    }

    public static void main(String[] args) throws IOException {
        new NIOClient().start();
    }
}
[客戶端一控制檯]
我是lzc
/127.0.0.1:13003==>我是lisi
lisi你好啊
/127.0.0.1:13003==>你好你好

[客戶端二控制檯]
/127.0.0.1:12977==>我是lzc
我是lisi
/127.0.0.1:12977==>lisi你好啊
你好你好
本作品採用《CC 協議》,轉載必須註明作者和本文連結