使用Java實現NIO

以下是一個使用 Java NIO 實現 Reactor 模型的簡單示例代碼,並附有詳細的註釋:

 
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.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

public class ReactorServer {
    public static void main(String[] args) throws IOException {
        // 創建 Selector 對象
        Selector selector = Selector.open();

        // 創建 ServerSocketChannel,並設置爲非阻塞模式
        ServerSocketChannel serverSocket = ServerSocketChannel.open();
        serverSocket.bind(new InetSocketAddress("127.0.0.1", 8888));
        serverSocket.configureBlocking(false);

        // 註冊 ServerSocketChannel 到 Selector,監聽連接事件
        serverSocket.register(selector, SelectionKey.OP_ACCEPT);

        while (true) {
            // 調用 select 方法阻塞等待事件發生
            selector.select();

            // 獲取觸發的事件集合
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

            while (keyIterator.hasNext()) {
                SelectionKey key = keyIterator.next();

                if (key.isAcceptable()) {
                    // 處理連接事件
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    client.register(selector, SelectionKey.OP_READ);
                } else if (key.isReadable()) {
                    // 處理讀取事件
                    SocketChannel client = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    int bytesRead = client.read(buffer);
                    if (bytesRead == -1) {
                        // 客戶端關閉連接
                        client.close();
                    } else if (bytesRead > 0) {
                        // 讀取數據並進行處理
                        buffer.flip();
                        byte[] data = new byte[buffer.remaining()];
                        buffer.get(data);
                        System.out.println("Received data: " + new String(data));
                        // 可以在這裏添加業務邏輯處理
                        // ...
                    }
                }

                // 從觸發的事件集合中移除當前事件
                keyIterator.remove();
            }
        }
    }
}

  

在這個示例中,我們使用了 Java NIO 的 Selector、ServerSocketChannel 和 SocketChannel 等組件實現了一個簡單的 Reactor 服務器。主要的事件循環部分通過調用 selector.select() 阻塞等待事件發生,然後遍歷處理觸發的事件。

希望這段代碼能夠幫助你更好地瞭解在 Java 中如何使用 NIO 實現 Reactor 模型。如果你有任何疑問或需要進一步解釋,請隨時告訴我。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章