Java NIO示例:多人網路聊天室
阿新 • • 發佈:2018-12-12
一個多客戶端聊天室,支援多客戶端聊天,有如下功能:
- 功能1: 客戶端通過Java NIO連線到服務端,支援多客戶端的連線
- 功能2:客戶端初次連線時,服務端提示輸入暱稱,如果暱稱已經有人使用,提示重新輸入,如果暱稱唯一,則登入成功,之後傳送訊息都需要按照規定格式帶著暱稱傳送訊息
- 功能3:客戶端登入後,傳送已經設定好的歡迎資訊和線上人數給客戶端,並且通知其他客戶端該客戶端上線
- 功能4:伺服器收到已登入客戶端輸入內容,轉發至其他登入客戶端。
- 功能5 TODO:客戶端下線檢測 方案是:客戶端線上的時候傳送心跳,服務端用TimeCacheMap自動刪除過期物件,同時通知線上使用者刪掉的使用者下線。
下面演示下效果,程式碼見附錄!
啟動伺服器,監聽某個埠
伺服器console
Server is listening now...
啟動一個客戶端,連線伺服器
伺服器console
Server is listening now... Server is listening from client :/127.0.0.1:50206
客戶端console
Please input your name.
客戶端輸入一個暱稱
服務端console
Server is listening now... Server is listening from client :/127.0.0.1:50206 Server is listening from client /127.0.0.1:50206 data rev is: byr1#@#
客戶端console
Please input your name. byr1 welcome byr1 to chat room! Online numbers:1
再啟動另外一個客戶端,並輸入暱稱
服務端console
Server is listening now... Server is listening from client :/127.0.0.1:50206 Server is listening from client /127.0.0.1:50206 data rev is: byr1#@# Server is listening from client :/127.0.0.1:50261 Server is listening from client /127.0.0.1:50261 data rev is: byr2#@#
客戶端byr1 console
Please input your name. byr1 welcome byr1 to chat room! Online numbers:1 welcome byr2 to chat room! Online numbers:2
客戶端byr2 console
Please input your name. byr2 welcome byr2 to chat room! Online numbers:2
客戶端byr1傳送一個訊息,客戶byr2回一條訊息
服務端console
Server is listening now... Server is listening from client :/127.0.0.1:50206 Server is listening from client /127.0.0.1:50206 data rev is: byr1#@# Server is listening from client :/127.0.0.1:50261 Server is listening from client /127.0.0.1:50261 data rev is: byr2#@# Server is listening from client /127.0.0.1:50206 data rev is: byr1#@#hello byr2, a nice day, isn't it? Server is listening from client /127.0.0.1:50261 data rev is: byr2#@#fine
客戶端byr1 console
Please input your name. byr1 welcome byr1 to chat room! Online numbers:1 welcome byr2 to chat room! Online numbers:2 hello byr2, a nice day, isn't it? byr2 say fine
客戶端byr2 console
Please input your name. byr2 welcome byr2 to chat room! Online numbers:2 byr1 say hello byr2, a nice day, isn't it? fine
附錄:server和client程式碼
server程式碼
package com.huahuiyang.channel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.Channel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.HashSet; import java.util.Iterator; import java.util.Set; /** * 網路多客戶端聊天室 * 功能1: 客戶端通過Java NIO連線到服務端,支援多客戶端的連線 * 功能2:客戶端初次連線時,服務端提示輸入暱稱,如果暱稱已經有人使用,提示重新輸入,如果暱稱唯一,則登入成功,之後傳送訊息都需要按照規定格式帶著暱稱傳送訊息 * 功能3:客戶端登入後,傳送已經設定好的歡迎資訊和線上人數給客戶端,並且通知其他客戶端該客戶端上線 * 功能4:伺服器收到已登入客戶端輸入內容,轉發至其他登入客戶端。 * * TODO 客戶端下線檢測 */ public class ChatRoomServer { private Selector selector = null; static final int port = 9999; private Charset charset = Charset.forName("UTF-8"); //用來記錄線上人數,以及暱稱 private static HashSet<String> users = new HashSet<String>(); private static String USER_EXIST = "system message: user exist, please change a name"; //相當於自定義協議格式,與客戶端協商好 private static String USER_CONTENT_SPILIT = "#@#"; private static boolean flag = false; public void init() throws IOException { selector = Selector.open(); ServerSocketChannel server = ServerSocketChannel.open(); server.bind(new InetSocketAddress(port)); //非阻塞的方式 server.configureBlocking(false); //註冊到選擇器上,設定為監聽狀態 server.register(selector, SelectionKey.OP_ACCEPT); System.out.println("Server is listening now..."); while(true) { int readyChannels = selector.select(); if(readyChannels == 0) continue; Set selectedKeys = selector.selectedKeys(); //可以通過這個方法,知道可用通道的集合 Iterator keyIterator = selectedKeys.iterator(); while(keyIterator.hasNext()) { SelectionKey sk = (SelectionKey) keyIterator.next(); keyIterator.remove(); dealWithSelectionKey(server,sk); } } } public void dealWithSelectionKey(ServerSocketChannel server,SelectionKey sk) throws IOException { if(sk.isAcceptable()) { SocketChannel sc = server.accept(); //非阻塞模式 sc.configureBlocking(false); //註冊選擇器,並設定為讀取模式,收到一個連線請求,然後起一個SocketChannel,並註冊到selector上,之後這個連線的資料,就由這個SocketChannel處理 sc.register(selector, SelectionKey.OP_READ); //將此對應的channel設定為準備接受其他客戶端請求 sk.interestOps(SelectionKey.OP_ACCEPT); System.out.println("Server is listening from client :" + sc.getRemoteAddress()); sc.write(charset.encode("Please input your name.")); } //處理來自客戶端的資料讀取請求 if(sk.isReadable()) { //返回該SelectionKey對應的 Channel,其中有資料需要讀取 SocketChannel sc = (SocketChannel)sk.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); StringBuilder content = new StringBuilder(); try { while(sc.read(buff) > 0) { buff.flip(); content.append(charset.decode(buff)); } System.out.println("Server is listening from client " + sc.getRemoteAddress() + " data rev is: " + content); //將此對應的channel設定為準備下一次接受資料 sk.interestOps(SelectionKey.OP_READ); } catch (IOException io) { sk.cancel(); if(sk.channel() != null) { sk.channel().close(); } } if(content.length() > 0) { String[] arrayContent = content.toString().split(USER_CONTENT_SPILIT); //註冊使用者 if(arrayContent != null && arrayContent.length ==1) { String name = arrayContent[0]; if(users.contains(name)) { sc.write(charset.encode(USER_EXIST)); } else { users.add(name); int num = OnlineNum(selector); String message = "welcome "+name+" to chat room! Online numbers:"+num; BroadCast(selector, null, message); } } //註冊完了,傳送訊息 else if(arrayContent != null && arrayContent.length >1){ String name = arrayContent[0]; String message = content.substring(name.length()+USER_CONTENT_SPILIT.length()); message = name + " say " + message; if(users.contains(name)) { //不回發給傳送此內容的客戶端 BroadCast(selector, sc, message); } } } } } //TODO 要是能檢測下線,就不用這麼統計了 public static int OnlineNum(Selector selector) { int res = 0; for(SelectionKey key : selector.keys()) { Channel targetchannel = key.channel(); if(targetchannel instanceof SocketChannel) { res++; } } return res; } public void BroadCast(Selector selector, SocketChannel except, String content) throws IOException { //廣播資料到所有的SocketChannel中 for(SelectionKey key : selector.keys()) { Channel targetchannel = key.channel(); //如果except不為空,不回發給傳送此內容的客戶端 if(targetchannel instanceof SocketChannel && targetchannel!=except) { SocketChannel dest = (SocketChannel)targetchannel; dest.write(charset.encode(content)); } } } public static void main(String[] args) throws IOException { new ChatRoomServer().init(); } }
client程式碼
package com.huahuiyang.channel; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.SocketChannel; import java.nio.charset.Charset; import java.util.Iterator; import java.util.Scanner; import java.util.Set; public class ChatRoomClient { private Selector selector = null; static final int port = 9999; private Charset charset = Charset.forName("UTF-8"); private SocketChannel sc = null; private String name = ""; private static String USER_EXIST = "system message: user exist, please change a name"; private static String USER_CONTENT_SPILIT = "#@#"; public void init() throws IOException { selector = Selector.open(); //連線遠端主機的IP和埠 sc = SocketChannel.open(new InetSocketAddress("127.0.0.1",port)); sc.configureBlocking(false); sc.register(selector, SelectionKey.OP_READ); //開闢一個新執行緒來讀取從伺服器端的資料 new Thread(new ClientThread()).start(); //在主執行緒中 從鍵盤讀取資料輸入到伺服器端 Scanner scan = new Scanner(System.in); while(scan.hasNextLine()) { String line = scan.nextLine(); if("".equals(line)) continue; //不允許發空訊息 if("".equals(name)) { name = line; line = name+USER_CONTENT_SPILIT; } else { line = name+USER_CONTENT_SPILIT+line; } sc.write(charset.encode(line));//sc既能寫也能讀,這邊是寫 } } private class ClientThread implements Runnable { public void run() { try { while(true) { int readyChannels = selector.select(); if(readyChannels == 0) continue; Set selectedKeys = selector.selectedKeys(); //可以通過這個方法,知道可用通道的集合 Iterator keyIterator = selectedKeys.iterator(); while(keyIterator.hasNext()) { SelectionKey sk = (SelectionKey) keyIterator.next(); keyIterator.remove(); dealWithSelectionKey(sk); } } } catch (IOException io) {} } private void dealWithSelectionKey(SelectionKey sk) throws IOException { if(sk.isReadable()) { //使用 NIO 讀取 Channel中的資料,這個和全域性變數sc是一樣的,因為只註冊了一個SocketChannel //sc既能寫也能讀,這邊是讀 SocketChannel sc = (SocketChannel)sk.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); String content = ""; while(sc.read(buff) > 0) { buff.flip(); content += charset.decode(buff); } //若系統傳送通知名字已經存在,則需要換個暱稱 if(USER_EXIST.equals(content)) { name = ""; } System.out.println(content); sk.interestOps(SelectionKey.OP_READ); } } } public static void main(String[] args) throws IOException { new ChatRoomClient().init(); } }
E-mail: [email protected] https://www.linkedin.com/in/huahuiyang/