NIO 實作多人聊天室的案例
服務端
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.nio.charset.Charset; /** * 聊天室服務端 */ public class NServer { private Selector selector = null; static final int PORT = 30000; private Charset charset = Charset.forName("UTF-8"); ServerSocketChannel server = null; public void init() throws IOException { selector = Selector.open(); server = ServerSocketChannel.open(); InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT); // 將該 ServerSocketChannel 系結到指定 IP 地址 server.bind(isa); //設定為以非阻塞方式作業 server.configureBlocking(false); // 將 server 注冊到指定的 Selector server.register(selector, SelectionKey.OP_ACCEPT); while (selector.select() > 0) { for (SelectionKey sk : selector.selectedKeys()) { // 從 selector 上的已選擇 Key 集中洗掉正在處理的 SelectionKey selector.selectedKeys().remove(sk); // 如果 sk 對應 channel 包含客戶端的連接請求 if (sk.isAcceptable()) { // 接受請求 SocketChannel sc = server.accept(); // 采用非阻塞模式 sc.configureBlocking(false); // 將該 SocketChannel 也注冊到 selector sc.register(selector, SelectionKey.OP_READ); // 將 sk 對應的 channel 設定成準備接受其他請求 sk.interestOps(SelectionKey.OP_ACCEPT); } // 如果 sk 對應的channel 有資料需要讀取 if (sk.isReadable()) { SocketChannel sc = (SocketChannel) sk.channel(); ByteBuffer buffer = ByteBuffer.allocate(1024); String content = ""; try { // 讀取資料操作 while (sc.read(buffer) > 0) { buffer.flip(); content += charset.decode(buffer); } System.out.println("讀取的資料: " + content); sk.interestOps(SelectionKey.OP_READ); } catch (IOException e) { sk.cancel(); if (sk.channel() != null) { sk.channel().close(); } } // 如果 content 的長度大于 0,即聊天資訊不為空 if (content.length() > 0) { // 遍歷該 selector 里注冊的所有 SelectionKey for (SelectionKey key : selector.keys()) { // 獲取 channel Channel targetChannel = key.channel(); // 如果該 channel 是 SocketChannel if (targetChannel instanceof SocketChannel) { // 將讀到的內容寫到該 channel 中 SocketChannel dest = (SocketChannel) targetChannel; dest.write(charset.encode(content)); } } } } } } } public static void main(String[] args) throws IOException { new NServer().init(); } }
啟動時建立一個可監聽連接請求的 ServerSocketChannel,并注冊到 Selector,接著直接采用回圈不斷監聽 Selector 物件的 select() 方法回傳值,大于0時,處理該 Selector 上所有被選擇的 SelectionKey,
服務端僅需監聽兩種操作:連接和讀取資料,
處理連接操作時,只需將連接完成后產生的 SocketChannel 注冊到指定的 Selector 物件;
處理讀取資料時,先從該 Socket 中讀取資料,再將資料寫入 Selector 上注冊的所有 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.Scanner; /** * 聊天室客戶端 */ public class NClient { private Selector selector = null; static final int PORT = 30000; private Charset charset = Charset.forName("UTF-8"); private SocketChannel sc = null; public void init() throws IOException { selector = Selector.open(); InetSocketAddress isa = new InetSocketAddress("127.0.0.1", PORT); // 打開套接字通道并將其連接到遠程地址 sc = SocketChannel.open(isa); // 設定為非阻塞模式 sc.configureBlocking(false); // 注冊到 selector sc.register(selector, SelectionKey.OP_READ); new ClientThread().start(); // 創建鍵盤輸入流 Scanner scan = new Scanner(System.in); while (scan.hasNextLine()) { String line = scan.nextLine(); // 將鍵盤大忽如的內容輸出到 SocketChannel 中 sc.write(charset.encode(line)); } } private class ClientThread extends Thread { @Override public void run() { try { while (selector.select() > 0) { for (SelectionKey sk : selector.selectedKeys()) { // 從 set集合洗掉正在處理的 SelectionKey selector.selectedKeys().remove(sk); // 如果 sk 對應的 channel 中有可讀資料 if (sk.isReadable()) { // 使用 NIO 讀取 channel 中的資料 SocketChannel sc = (SocketChannel) sk.channel(); ByteBuffer buff = ByteBuffer.allocate(1024); String content = ""; while (sc.read(buff) > 0) { sc.read(buff); buff.flip(); content += charset.decode(buff); } System.out.println("聊天資訊: " + content); // 為下一次讀取做準備 sk.interestOps(SelectionKey.OP_READ); } } } } catch (IOException e) { e.printStackTrace(); } } } public static void main(String[] args) throws IOException { new NClient().init(); } }
相比于服務端程式,客戶端要簡單一些,只有一個 SocketChannel ,將其注冊到指定的 Selector 后,程式啟動另一個執行緒來監聽該 Selector 即可,
分別啟動兩個程式后,可以在客戶點輸入內容,在服務端就可以讀取到輸入的內

服務端內容:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/549274.html
標籤:其他
上一篇:社交媒體營銷教程_編程入門自學教程_菜鳥教程-免費教程分享
下一篇:單元測驗案例
