第三章—Java NIO程式設計:(7)群聊系統
阿新 • • 發佈:2022-03-08
一、案例要求
例項要求:
- 編寫一個 NIO 群聊系統, 實現伺服器端和客戶端之間的資料簡單通訊(非 阻塞)
- 實現多人群聊
- 伺服器端: 可以監測使用者上線, 離線,並實現訊息轉發功能
- 客戶端: 通過channel 可以無阻塞傳送訊息給其它所有使用者,同時可以接受 其它使用者傳送的訊息(有伺服器轉發得到)
- 目的: 進一步理解NIO非阻塞網路程式設計機制
實現效果:
思路步驟:
- 先編寫伺服器端
- 伺服器啟動並監聽 6667
- 伺服器接收客戶端資訊,並實現轉發 [處理上線和離線]
- 編寫客戶端
- 連線伺服器
- 傳送訊息
- 接收伺服器訊息
二、伺服器端
public class GroupChatServer {
//定義屬性
private Selector selector;
private ServerSocketChannel listenChannel;
private static final int PORT = 6667;
//構造器
//初始化工作
public GroupChatServer() {
try {
//得到選擇器
selector = Selector.open();
System.out.println("selector = " + selector);
//獲取 ServerSocketChannel
listenChannel = ServerSocketChannel.open();
//繫結埠
listenChannel.socket().bind(new InetSocketAddress(PORT));
//設定非阻塞模式
listenChannel.configureBlocking(false);
//將該 listenChannel 註冊到selector
listenChannel.register(selector, SelectionKey.OP_ACCEPT);
} catch (IOException e) {
e.printStackTrace();
}
}
//伺服器監聽
public void listen() {
System.out.println("監聽執行緒: " + Thread.currentThread().getName());
try {
//迴圈處理
while (true) {
int count = selector.select();
//有事件需要處理
if (count > 0) {
//遍歷得到的 selectionKey 集合
Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
while (keyIterator.hasNext()) {
//取出 SelectionKey
SelectionKey key = keyIterator.next();
//監聽到accept
if (key.isAcceptable()) {
//建立一個SocketChannel
SocketChannel socketChannel = listenChannel.accept();
//設定非阻塞模式
socketChannel.configureBlocking(false);
//註冊到選擇器
socketChannel.register(selector, SelectionKey.OP_READ);
//提示
System.out.println(socketChannel.getRemoteAddress() + " 上線");
}
//通道傳送read事件,即通道是可讀的狀態
if (key.isReadable()) {
//處理讀(專門寫方法...)
read(key);
}
//當前的key 刪除,防止重複處理
keyIterator.remove();
}
} else {
System.out.println("等待...");
}
}
}catch (IOException e) {
e.printStackTrace();
}
}
//讀取客戶端資訊
private void read(SelectionKey key) {
//得到關聯的 Channel
SocketChannel socketChannel = null;
try {
//得到 channel
socketChannel = (SocketChannel) key.channel();
//建立 buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
//讀取資料
int count = socketChannel.read(buffer);
//根據 count 的值去做處理
if (count > 0) {
//把快取區的資料轉成字串
String msg = new String(buffer.array());
//輸出該訊息
System.out.println("form 客戶端:" + msg);
//轉發訊息:向其它的客戶端轉發訊息(去掉自己), 專門寫一個方法來處理
sentInfoToOtherClients(msg, socketChannel);
}
}catch (IOException e) {
try {
System.out.println(socketChannel.getRemoteAddress() + " 離線了..");
//取消註冊
key.cancel();
//關閉通道
socketChannel.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//轉發訊息給其它客戶(通道)
private void sentInfoToOtherClients(String msg, SocketChannel self) throws IOException{
System.out.println("伺服器轉發訊息中...");
System.out.println("伺服器轉發資料給客戶端執行緒: " + Thread.currentThread().getName());
//遍歷 所有註冊到selector 上的 SocketChannel,並排除 self
for (SelectionKey key : selector.keys()) {
//通過 key 獲取到對應的 channel
Channel targetChannel = key.channel();
//排除自己
if (targetChannel instanceof SocketChannel && targetChannel != self) {
//轉型
SocketChannel dest = (SocketChannel) targetChannel;
//將msg儲存到 buffer
ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
//將 buffer 的資料寫入通道
dest.write(buffer);
}
}
}
public static void main(String[] args) {
//建立伺服器物件
GroupChatServer groupChatServer = new GroupChatServer();
groupChatServer.listen();
}
}
三、客戶端
public class GroupChatClient {
//定義相關的屬性
// 伺服器的ip
private static final String HOST = "127.0.0.1";
//伺服器埠
private static final Integer PORT = 6667;
private Selector selector;
private SocketChannel socketChannel;
private String userName;
//構造器,完成初始化工作
public GroupChatClient() {
try {
//獲取選擇器
selector = Selector.open();
System.out.println("selector = " + selector);
//連線伺服器
socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
//設定非阻塞
socketChannel.configureBlocking(false);
//將 socketChannel 註冊到 selector
socketChannel.register(selector, SelectionKey.OP_READ);
//得到 userName
userName = socketChannel.getLocalAddress().toString().substring(1);
System.out.println(userName + " is ok...");
} catch (IOException e) {
e.printStackTrace();
}
}
//向伺服器傳送訊息
public void sendInfo(String info) {
info = userName + "說:" + info;
try {
socketChannel.write(ByteBuffer.wrap(info.getBytes()));
} catch (IOException e) {
e.printStackTrace();
}
}
//讀取從伺服器端回覆的訊息
public void readInfo() {
try {
int readChannels = selector.select();
//有可以用的通道
if (readChannels > 0) {
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext()) {
SelectionKey key = iterator.next();
if (key.isReadable()) {
//得到相關的通道
SocketChannel socketChannel = (SocketChannel) key.channel();
//得到一個 Buffer
ByteBuffer buffer = ByteBuffer.allocate(1024);
//讀取
socketChannel.read(buffer);
//把讀到的緩衝區的資料轉成字串
String msg = new String(buffer.array());
System.out.println(msg.trim());
}
}
//刪除當前的selectionKey, 防止重複操作
iterator.remove();
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
//啟動客戶端
GroupChatClient chatClient = new GroupChatClient();
//啟動一個執行緒,每隔3秒,讀取從伺服器傳送的資料
new Thread() {
@Override
public void run() {
System.out.println("讀取資訊");
chatClient.readInfo();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}.start();
//傳送資料給伺服器
Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()) {
String s = scanner.nextLine();
chatClient.sendInfo(s);
}
}
}