我想使用 java NIO 编写 java tcp socket 编程。它工作正常。但是我使用相同的选择器来接受客户端的读取和写入。
如何创建不同的选择器来接受 java NIO 中的新连接、读取和写入。有没有在线帮助。
实际上,当我忙于阅读或编写时,我的选择器会使用更多迭代器。因此,如果连接的客户端数量更多,那么接受新连接的性能就会变慢。但我不希望接受客户变慢
// 创建一个选择器并注册两个套接字通道 Selector selector = null; try { // 创建选择器 selector = Selector.open();
// Create two non-blocking sockets. This method is implemented in
// e173 Creating a Non-Blocking Socket.
SocketChannel sChannel1 = createSocketChannel("hostname.com", 80);
SocketChannel sChannel2 = createSocketChannel("hostname.com", 80);
// Register the channel with selector, listening for all events
sChannel1.register(selector, sChannel1.validOps());
sChannel2.register(selector, sChannel1.validOps());
} catch (IOException e) {
}
// Wait for events
while (true) {
try {
// Wait for an event
selector.select();
} catch (IOException e) {
// Handle error with selector
break;
}
// Get list of selection keys with pending events
Iterator it = selector.selectedKeys().iterator();
// Process each key at a time
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();
try {
processSelectionKey(selKey);
} catch (IOException e) {
// Handle error with channel and unregister
selKey.cancel();
}
}
}
public void processSelectionKey(SelectionKey selKey) throws IOException {
// Since the ready operations are cumulative,
// need to check readiness for each operation
if (selKey.isValid() && selKey.isConnectable()) {
// Get channel with connection request
SocketChannel sChannel = (SocketChannel)selKey.channel();
boolean success = sChannel.finishConnect();
if (!success) {
// An error occurred; handle it
// Unregister the channel with this selector
selKey.cancel();
}
}
if (selKey.isValid() && selKey.isReadable()) {
// Get channel with bytes to read
SocketChannel sChannel = (SocketChannel)selKey.channel();
// See e174 Reading from a SocketChannel
}
if (selKey.isValid() && selKey.isWritable()) {
// Get channel that's ready for more bytes
SocketChannel sChannel = (SocketChannel)selKey.channel();
}
}
谢谢迪帕克