0

我正在努力理解如何使用SelectorDatagramChannel.

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 的知识的理解。

问题。

  1. OP_READ我应该在第OP_WRITER一次注册频道吗?
  2. 或者我应该像上面那样更新interestOps?
  3. 总是会selectedKeys()返回一组单个元素吗?
4

0 回答 0