使用 1 个套接字通道进行 2 路"real-time communictation"



我正在接收一个连续的数据流,我正在保存到ByteBuffer。有时我需要写入通道,但是,重要的是不要丢失任何数据。有可能使用选择器来解决这个问题吗?

如果我不断检查通道状态的选择器,它总是说通道当前正在读取,就像没有机会执行写入一样。我不能使用多个连接,因为服务器不支持。

        this.socketChannel = SocketChannel.open();
        this.socketChannel.configureBlocking(false);
        this.socketChannel.connect(new InetSocketAddress(IP, this.port));

   try {
        this.selector = Selector.open();
        int interestSet = SelectionKey.OP_READ | SelectionKey.OP_WRITE;
        SelectionKey selectionKey = this.socketChannel.register(selector, interestSet);
        while (selector.select() > -1) {
            // Wait for an event one of the registered channels
            // Iterate over the set of keys for which events are available
            Iterator selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = (SelectionKey) selectedKeys.next();
                selectedKeys.remove();
                try {
                    if (!key.isValid()) {
                        continue;
                    } else if (key.isReadable()) {
                        System.out.println("readable");
                    } else if (key.isWritable()) {
                        System.out.println("writable");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace();
    }

编辑:抱歉我没有补充更多的信息。这是我的代码中很重要的一部分。它总是打印"readable"到控制台,我希望isWritable块也被执行。

提前感谢Honza

您正在使用else if操作符,因此如果您的key可读检查它是否可写将不会执行,但这并不意味着通道不是可写

实际上它可以同时是可读可写。但是在你的程序中,如果它是可读的,你就不用检查是否可写

if代替else-if,看结果

最新更新