咖啡汪 2021-02-19 09:16 采纳率: 0%
浏览 57

socketChannel 无法注册 Selector 对 OP_ACCEPT 进行监测

public static void main(String[] args) throws IOException {

  Selector selector = Selector.open();
  SocketChannel socketChannel = SocketChannel.open();
  //The Channel must be in non-blocking mode to be used with a Selector.
    // This means that you cannot use FileChannel's with a Selector since FileChannel's cannot be switched into non-blocking mode.
    // Socket channels will work fine though.
  socketChannel.configureBlocking(false);
  //If you are interested in more than one event, OR the constants together, like this:
  int interestSet = SelectionKey.OP_ACCEPT;
  SelectionKey selectionKey = socketChannel.register(selector, interestSet);

  int interestSets = selectionKey.interestOps();
  boolean isInterestedInAccept = (interestSets & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT;
    System.out.println("flag: " + isInterestedInAccept);
}

报错: 

Connected to the target VM, address: '127.0.0.1:51931', transport: 'socket'<br /> Exception in thread "main" java.lang.IllegalArgumentException<br />     at java.nio.channels.spi.AbstractSelectableChannel.register(AbstractSelectableChannel.java:199)<br />     at java.nio.channels.SelectableChannel.register(SelectableChannel.java:280)<br />     at com.deodar.web.controller.nio.SelectorTest.main(SelectorTest.java:31)<br /> Disconnected from the target VM, address: '127.0.0.1:51931', transport: 'socket'

Process finished with exit code 1

源码: 

 

public final SelectionKey register(Selector sel, int ops,
                                   Object att)
    throws ClosedChannelException
{
    synchronized (regLock) {
        if (!isOpen())
            throw new ClosedChannelException();
        if ((ops & ~validOps()) != 0)
            throw new IllegalArgumentException();
        if (blocking)
            throw new IllegalBlockingModeException();
        SelectionKey k = findKey(sel);
        if (k != null) {
            k.interestOps(ops);
            k.attach(att);
        }
        if (k == null) {
            // New registration
            synchronized (keyLock) {
                if (!isOpen())
                    throw new ClosedChannelException();
                k = ((AbstractSelector)sel).register(this, ops, att);
                addKey(k);
            }
        }
        return k;
    }
}
  • 写回答

1条回答 默认 最新

  • CSDN-Ada助手 CSDN-AI 官方账号 2022-09-07 18:00
    关注
    不知道你这个问题是否已经解决, 如果还没有解决的话:

    如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 以帮助更多的人 ^-^
    评论

报告相同问题?

悬赏问题

  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等
  • ¥15 matlab 用yalmip搭建模型,cplex求解,线性化处理的方法
  • ¥15 qt6.6.3 基于百度云的语音识别 不会改
  • ¥15 关于#目标检测#的问题:大概就是类似后台自动检测某下架商品的库存,在他监测到该商品上架并且可以购买的瞬间点击立即购买下单
  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥20 测距传感器数据手册i2c