91超碰碰碰碰久久久久久综合_超碰av人澡人澡人澡人澡人掠_国产黄大片在线观看画质优化_txt小说免费全本

溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

怎么使用Java?NIO實現多人聊天室

發布時間:2021-11-24 13:31:14 來源:億速云 閱讀:129 作者:iii 欄目:開發技術

本篇內容主要講解“怎么使用Java NIO實現多人聊天室”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“怎么使用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");
    }

}

到此,相信大家對“怎么使用Java NIO實現多人聊天室”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!

向AI問一下細節

免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI

多伦县| 新乡市| 长宁县| 高唐县| 合江县| 高邑县| 岚皋县| 札达县| 申扎县| 萍乡市| 高碑店市| 海原县| 琼海市| 诸暨市| 金沙县| 连城县| 康定县| 广平县| 淮南市| 庄浪县| 景东| 科尔| 巴彦淖尔市| 育儿| 南昌市| 周宁县| 鹤峰县| 嵩明县| 合川市| 加查县| 平舆县| 惠安县| 宿迁市| 新营市| 班戈县| 南康市| 秦皇岛市| 丁青县| 讷河市| 武定县| 南平市|