4. 彤哥說netty系列之Java NIO實現群聊(自己跟自己聊上癮了)

你好,我是彤哥,本篇是netty系列的第四篇。

歡迎來我的公從號彤哥讀源碼系統地學習源碼&架構的知識。

簡介

上一章我們一起學習了Java中的BIO/NIO/AIO的故事,本章將帶着大家一起使用純純的NIO實現一個越聊越上癮的“群聊系統”。

業務邏輯分析

首先,我們先來分析一下群聊的功能點:

(1)加入群聊,並通知其他人;

(2)發言,並通知其他人;

(3)退出群聊,並通知其他人;

一個簡單的群聊系統差不多這三個功能足夠了,為了方便記錄用戶信息,當用戶加入群聊的時候自動給他分配一個用戶ID。

業務實現

上代碼:

// 這是一個內部類
private static class ChatHolder {
    // 我們只用了一個線程,用普通的HashMap也可以
    static final Map<SocketChannel, String> USER_MAP = new ConcurrentHashMap<>();

    /**
     * 加入群聊
     * @param socketChannel
     */
    static void join(SocketChannel socketChannel) {
        // 有人加入就給他分配一個id,本文來源於公從號“彤哥讀源碼”
        String userId = "用戶"+ ThreadLocalRandom.current().nextInt(Integer.MAX_VALUE);
        send(socketChannel, "您的id為:" + userId + "\n\r");

        for (SocketChannel channel : USER_MAP.keySet()) {
            send(channel, userId + " 加入了群聊" + "\n\r");
        }

        // 將當前用戶加入到map中
        USER_MAP.put(socketChannel, userId);
    }

    /**
     * 退出群聊
     * @param socketChannel
     */
    static void quit(SocketChannel socketChannel) {
        String userId = USER_MAP.get(socketChannel);
        send(socketChannel, "您退出了群聊" + "\n\r");
        USER_MAP.remove(socketChannel);

        for (SocketChannel channel : USER_MAP.keySet()) {
            if (channel != socketChannel) {
                send(channel, userId + " 退出了群聊" + "\n\r");
            }
        }
    }

    /**
     * 擴散說話的內容
     * @param socketChannel
     * @param content
     */
    public static void propagate(SocketChannel socketChannel, String content) {
        String userId = USER_MAP.get(socketChannel);
        for (SocketChannel channel : USER_MAP.keySet()) {
            if (channel != socketChannel) {
                send(channel, userId + ": " + content + "\n\r");
            }
        }
    }

    /**
     * 發送消息
     * @param socketChannel
     * @param msg
     */
    static void send(SocketChannel socketChannel, String msg) {
        try {
            ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
            writeBuffer.put(msg.getBytes());
            writeBuffer.flip();
            socketChannel.write(writeBuffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

服務端代碼

服務端代碼直接使用上一章NIO的實現,只不過這裏要把上面實現的業務邏輯適時地插入到相應的事件中。

(1)accept事件,即連接建立的時候,說明加入了群聊;

(2)read事件,即讀取數據的時候,說明有人說話了;

(3)連接斷開的時候,說明退出了群聊;

OK,直接上代碼,為了與上一章的代碼作區分,彤哥特意加入了一些標記:

public class ChatServer {
    public static void main(String[] args) throws IOException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));
        serverSocketChannel.configureBlocking(false);
        // 將accept事件綁定到selector上
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            // 阻塞在select上
            selector.select();
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            // 遍歷selectKeys
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {
                SelectionKey selectionKey = iterator.next();
                // 如果是accept事件
                if (selectionKey.isAcceptable()) {
                    ServerSocketChannel ssc = (ServerSocketChannel) selectionKey.channel();
                    SocketChannel socketChannel = ssc.accept();
                    System.out.println("accept new conn: " + socketChannel.getRemoteAddress());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ);
                    // 加入群聊,本文來源於公從號“彤哥讀源碼”
                    ChatHolder.join(socketChannel);
                } else if (selectionKey.isReadable()) {
                    // 如果是讀取事件
                    SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    // 將數據讀入到buffer中
                    int length = socketChannel.read(buffer);
                    if (length > 0) {
                        buffer.flip();
                        byte[] bytes = new byte[buffer.remaining()];
                        // 將數據讀入到byte數組中
                        buffer.get(bytes);

                        // 換行符會跟着消息一起傳過來
                        String content = new String(bytes, "UTF-8").replace("\r\n", "");
                        if (content.equalsIgnoreCase("quit")) {
                            // 退出群聊,本文來源於公從號“彤哥讀源碼”
                            ChatHolder.quit(socketChannel);
                            selectionKey.cancel();
                            socketChannel.close();
                        } else {
                            // 擴散,本文來源於公從號“彤哥讀源碼”
                            ChatHolder.propagate(socketChannel, content);
                        }
                    }
                }
                iterator.remove();
            }
        }
    }
}

測試

打開四個XSHELL客戶端,分別連接telnet 127.0.0.1 8080,然後就可以開始群聊了。

彤哥發現,自己跟自己聊天也是會上癮的,完全停不下來,不行了,我再去自聊一會兒^^

總結

本文彤哥跟着大家一起實現了“群聊系統”,去掉註釋也就100行左右的代碼,是不是非常簡單?這就是NIO網絡編程的魅力,我發現寫網絡編程也上癮了^^

問題

這兩章我們都沒有用NIO實現客戶端,你知道怎麼實現嗎?

提示:服務端需要監聽accept事件,所以需要有一個ServerSocketChannel,而客戶端是直接去連服務器了,所以直接用SocketChannel就可以了,一個SocketChannel就相當於一個Connection。

最後,也歡迎來我的公從號彤哥讀源碼系統地學習源碼&架構的知識。

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理
【其他文章推薦】

※為什麼 USB CONNECTOR 是電子產業重要的元件?

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想要讓你的商品成為最夯、最多人討論的話題?網頁設計公司讓你強力曝光

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

※專營大陸快遞台灣服務

台灣快遞大陸的貨運公司有哪些呢?

您可能也會喜歡…