2

Java NIO を使用して単純なサーバー クライアント アプリケーションを作成しました。そこでは、接続の受け入れ、データの読み取り、および書き込みに単一のセレクターを使用しました。しかし、2番目のセレクターがデータを読み取り、3番目のセレクターがデータを書き込む間、1つのセレクターが接続の受け入れでビジーになるアプリケーションが必要です。

つまり、すべての負荷を単一のセレクターに入れたくありません。

これを達成する方法は?オンラインヘルプはありますか

ありがとうディーパック。

// セレクターを作成する Selector selector = Selector.open();

    // Create two non-blocking server sockets on 80 and 81
    ServerSocketChannel ssChannel1 = ServerSocketChannel.open();
    ssChannel1.configureBlocking(false);
    ssChannel1.socket().bind(new InetSocketAddress(80));

    // Register both channels with selector
    ssChannel1.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        // Wait for an event
        selector.select();

        // Get list of selection keys with pending events
        Iterator it = selector.selectedKeys().iterator();

        // Process each key
        while (it.hasNext()) {
            // Get the selection key
            SelectionKey selKey = (SelectionKey)it.next();

            // Remove it from the list to indicate that it is being processed
            it.remove();

            // Check if it's a connection request
            if (selKey.isAcceptable()) {
                // Get channel with connection request
                ServerSocketChannel ssChannel = (ServerSocketChannel)selKey.channel();

                // Accepting a Connection on a ServerSocketChannel
                SocketChannel sChannel = serverSocketChannel.accept();

    // If serverSocketChannel is non-blocking, sChannel may be null
    if (sChannel == null) {
        // There were no pending connection requests; try again later.
        // To be notified of connection requests,

    } else {
        // Use the socket channel to communicate with the client

    }

            }
        }
    }
4

2 に答える 2

5

を使用して、チャネルを複数のセレクターに登録することができregister(Selector sel, int ops)ます。次に、各セレクターに異なる関心操作を登録します。

// After the accepting a connection:
SelectionKey readKey = sChannel.register(readSelector, SelectionKey.OP_READ);

// When you have something to write:
SelectionKey writeKey = sChannel.register(writeSelector, SelectionKey.OP_WRITE); 
于 2009-05-25T14:37:50.667 に答える