1. 程式人生 > 其它 >NIO 實現非阻塞 Socket 通訊

NIO 實現非阻塞 Socket 通訊

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 即可。

分別啟動兩個程式後,可以在客戶點輸入內容,在服務端就可以讀取到輸入的內容:

服務端內容: