標籤:
一個多用戶端聊天室,支援多用戶端聊天,有如下功能:
- 功能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:50206Server is listening from client /127.0.0.1:50206 data rev is: byr1#@#
用戶端console
Please input your name.byr1welcome byr1 to chat room! Online numbers:1
再啟動另外一個用戶端,並輸入暱稱
服務端console
Server is listening now...Server is listening from client :/127.0.0.1:50206Server is listening from client /127.0.0.1:50206 data rev is: byr1#@#Server is listening from client :/127.0.0.1:50261Server is listening from client /127.0.0.1:50261 data rev is: byr2#@#
用戶端byr1 console
Please input your name.byr1welcome byr1 to chat room! Online numbers:1welcome byr2 to chat room! Online numbers:2
用戶端byr2 console
Please input your name.byr2welcome byr2 to chat room! Online numbers:2
用戶端byr1發送一個訊息,客戶byr2回一條訊息
服務端console
Server is listening now...Server is listening from client :/127.0.0.1:50206Server is listening from client /127.0.0.1:50206 data rev is: byr1#@#Server is listening from client :/127.0.0.1:50261Server 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.byr1welcome byr1 to chat room! Online numbers:1welcome byr2 to chat room! Online numbers:2hello byr2, a nice day, isn‘t it?byr2 say fine
用戶端byr2 console
Please input your name.byr2welcome byr2 to chat room! Online numbers:2byr1 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(); }}
Java NIO樣本:多人網路聊天室