Java 使用1个插座通道进行双向“焊接”;“实时通信”;

Java 使用1个插座通道进行双向“焊接”;“实时通信”;,java,socketchannel,Java,Socketchannel,我正在接收一个连续的数据流,并将其保存到ByteBuffer。 有时我需要写入通道,但重要的是不要丢失任何数据。是否可以使用选择器来解决此问题 如果我经常检查通道状态选择器,它总是说通道当前正在读取,好像没有机会执行写入。我无法使用多个连接,因为服务器不支持它 this.socketChannel = SocketChannel.open(); this.socketChannel.configureBlocking(false); this.s

我正在接收一个连续的数据流,并将其保存到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();
    }
编辑: 抱歉,我没有添加更多信息。这是我代码中的一个重要部分。它总是将“可读”打印到控制台,我希望isWritable块也能被执行


提前感谢,Honza

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

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


if
替换为
if
并查看结果。

请更具体一点。显示您编写的代码、任何错误或适用的堆栈跟踪等。听起来您对您的内容没有任何特定的协议