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
}
}
}
}