4. 彤哥說netty系列之Java NIO實現群聊(自己跟自己聊上癮了)
阿新 • • 發佈:2020-06-24
你好,我是彤哥,本篇是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。
最後,也歡迎來我的公從號彤哥讀原始碼系統地學習原始碼&架構的知識。