我正在努力理解如何使用Selector
和DatagramChannel
.
DatagramChannel server = DatagramChannel.open();
server.bind(...)
try (var selector = selector.open()) {
server.configureBlocking(false);
server.register(selector, ???); // OP_READ | OP_WRITE ??
while (!currentThread().isInterrupted()) {
if (selector.select() == 0) {
continue;
}
var keys = selector.selectedKeys(); // how many keys in there?
for (var key : keys) {
var channel = (DatagramChannel) key.channel();
if (key.isReadable()) {
var address = channel.receive(allocate(0));
if (address != null) {
log.debug("received from {}", address);
key.interestOps(key.interestOps() & ~OP_READ);
key.interestOps(key.interestOps() | OP_WRITE);
key.attach(address);
}
continue;
}
if (key.isWritable()) {
var buffer = ...
channel.send(buffer, (SocketAddress) key.attachment());
key.interestOps(key.interestOps() & ~OP_WRITE);
key.interestOps(key.interestOps() | OP_READ);
continue;
}
}
keys.clear();
}
}
困惑来自对基于 TCP 的知识的理解。
问题。
OP_READ
我应该在第OP_WRITER
一次注册频道吗?- 或者我应该像上面那样更新interestOps?
- 总是会
selectedKeys()
返回一组单个元素吗?