天天看點

Java-NIO實戰多人聊天室

NIO服務端

public class NioServer {

    /**
     * 啟動
     */
    public void start() throws IOException {
        /**
         * 1. 建立Selector
         */
        Selector selector = Selector.open();
        /**
         * 2. 通過ServerSocketChannel建立channel通道
         */
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        /**
         * 3. 為channel通道綁定監聽端口
         */
        serverSocketChannel.bind(new InetSocketAddress(8000));
        /**
         * 4. **設定channel為非阻塞模式**
         */
        serverSocketChannel.configureBlocking(false);
        /**
         * 5. 将channel注冊到selector上,監聽連接配接事件
         */
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("伺服器啟動成功!");

        /**
         * 6. 循環等待新接入的連接配接
         */
        for (;;) { // while(true) c for;;
            /**
             * TODO 擷取可用channel數量
             */
            int readyChannels = selector.select();

            /**
             * TODO 為什麼要這樣!!?
             */
            if (readyChannels == 0) continue;

            /**
             * 擷取可用channel的集合
             */
            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            Iterator iterator = selectionKeys.iterator();

            while (iterator.hasNext()) {
                /**
                 * selectionKey執行個體
                 */
                SelectionKey selectionKey = (SelectionKey) iterator.next();

                /**
                 * **移除Set中的目前selectionKey**
                 */
                iterator.remove();

                /**
                 * 7. 根據就緒狀态,調用對應方法處理業務邏輯
                 */
                /**
                 * 如果是 接入事件
                 */
                if (selectionKey.isAcceptable()) {
                    acceptHandler(serverSocketChannel, selector);
                }

                /**
                 * 如果是 可讀事件
                 */
                if (selectionKey.isReadable()) {
                    readHandler(selectionKey, selector);
                }
            }
        }
    }

    /**
     * 接入事件處理器
     */
    private void acceptHandler(ServerSocketChannel serverSocketChannel,
                               Selector selector)
            throws IOException {
        /**
         * 如果要是接入事件,建立socketChannel
         */
        SocketChannel socketChannel = serverSocketChannel.accept();

        /**
         * 将socketChannel設定為非阻塞工作模式
         */
        socketChannel.configureBlocking(false);

        /**
         * 将channel注冊到selector上,監聽 可讀事件
         */
        socketChannel.register(selector, SelectionKey.OP_READ);

        /**
         * 回複用戶端提示資訊
         */
        socketChannel.write(Charset.forName("UTF-8")
                .encode("你與聊天室裡其他人都不是朋友關系,請注意隐私安全"));
    }

    /**
     * 可讀事件處理器
     */
    private void readHandler(SelectionKey selectionKey, Selector selector)
            throws IOException {
        /**
         * 要從 selectionKey 中擷取到已經就緒的channel
         */
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

        /**
         * 建立buffer
         */
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        /**
         * 循環讀取用戶端請求資訊
         */
        String request = "";
        while (socketChannel.read(byteBuffer) > 0) {
            /**
             * 切換buffer為讀模式
             */
            byteBuffer.flip();

            /**
             * 讀取buffer中的内容
             */
            request += Charset.forName("UTF-8").decode(byteBuffer);
        }

        /**
         * 将channel再次注冊到selector上,監聽他的可讀事件
         */
        socketChannel.register(selector, SelectionKey.OP_READ);

        /**
         * 将用戶端發送的請求資訊 廣播給其他用戶端
         */
        if (request.length() > 0) {
            // 廣播給其他用戶端
            broadCast(selector, socketChannel, request);
        }
    }

    /**
     * 廣播給其他用戶端
     */
    private void broadCast(Selector selector,
                           SocketChannel sourceChannel, String request) {
        /**
         * 擷取到所有已接入的用戶端channel
         */
        Set<SelectionKey> selectionKeySet = selector.keys();

        /**
         * 循環向所有channel廣播資訊
         */
        selectionKeySet.forEach(selectionKey -> {
            Channel targetChannel = selectionKey.channel();

            // 剔除發消息的用戶端
            if (targetChannel instanceof SocketChannel
                    && targetChannel != sourceChannel) {
                try {
                    // 将資訊發送到targetChannel用戶端
                    ((SocketChannel) targetChannel).write(
                            Charset.forName("UTF-8").encode(request));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 主方法
     * @param args
     */
    public static void main(String[] args) throws IOException {
        new NioServer().start();
    }

}
           

NIO用戶端

public class NioClient {

    /**
     * 啟動
     */
    public void start(String nickname) throws IOException {
        /**
         * 連接配接伺服器端
         */
        SocketChannel socketChannel = SocketChannel.open(
                new InetSocketAddress("127.0.0.1", 8000));

        /**
         * 接收伺服器端響應
         */
        // 新開線程,專門負責來接收伺服器端的響應資料
        // selector , socketChannel , 注冊
        Selector selector = Selector.open();
        socketChannel.configureBlocking(false);
        socketChannel.register(selector, SelectionKey.OP_READ);
        new Thread(new NioClientHandler(selector)).start();

        /**
         * 向伺服器端發送資料
         */
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String request = scanner.nextLine();
            if (request != null && request.length() > 0) {
                socketChannel.write(
                        Charset.forName("UTF-8")
                                .encode(nickname + " : " + request));
            }
        }

    }
    public static void main(String[] args) throws IOException {
//        new NioClient().start();
    }
}
           

用戶端線程,處理伺服器端響應的的消息

public class NioClientHandler implements Runnable {
    private Selector selector;

    public NioClientHandler(Selector selector) {
        this.selector = selector;
    }

    @Override
    public void run() {

        try {
            for (;;) {
                int readyChannels = selector.select();

                if (readyChannels == 0) continue;

                /**
                 * 擷取可用channel的集合
                 */
                Set<SelectionKey> selectionKeys = selector.selectedKeys();

                Iterator iterator = selectionKeys.iterator();

                while (iterator.hasNext()) {
                    /**
                     * selectionKey執行個體
                     */
                    SelectionKey selectionKey = (SelectionKey) iterator.next();

                    /**
                     * **移除Set中的目前selectionKey**
                     */
                    iterator.remove();

                    /**
                     * 7. 根據就緒狀态,調用對應方法處理業務邏輯
                     */

                    /**
                     * 如果是 可讀事件
                     */
                    if (selectionKey.isReadable()) {
                        readHandler(selectionKey, selector);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 可讀事件處理器
     */
    private void readHandler(SelectionKey selectionKey, Selector selector)
            throws IOException {
        /**
         * 要從 selectionKey 中擷取到已經就緒的channel
         */
        SocketChannel socketChannel = (SocketChannel) selectionKey.channel();

        /**
         * 建立buffer
         */
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

        /**
         * 循環讀取伺服器端響應資訊
         */
        String response = "";
        while (socketChannel.read(byteBuffer) > 0) {
            /**
             * 切換buffer為讀模式
             */
            byteBuffer.flip();

            /**
             * 讀取buffer中的内容
             */
            response += Charset.forName("UTF-8").decode(byteBuffer);
        }

        /**
         * 将channel再次注冊到selector上,監聽他的可讀事件
         */
        socketChannel.register(selector, SelectionKey.OP_READ);

        /**
         * 将伺服器端響應資訊列印到本地
         */
        if (response.length() > 0) {
            System.out.println(response);
        }
    }
}
           

我們定義三個用戶端,模拟三個使用者在聊天室發送消息

public class AClient {

    public static void main(String[] args)
            throws IOException {
        new NioClient().start("AClient");
    }
}

public class BClient {

    public static void main(String[] args)
            throws IOException {
        new NioClient().start("BClient");
    }
}

public class CClient {

    public static void main(String[] args)
            throws IOException {
        new NioClient().start("CClient");
    }

}
           

NIO 聊天室到此結束

繼續閱讀