【问题标题】:Using 1 SocketChannel for 2-way "real-time communictation"使用 1 个 SocketChannel 进行 2 路“实时通信”
【发布时间】:2015-11-29 11:20:28
【问题描述】:

我正在接收一个连续的数据流,并将其保存到 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

【问题讨论】:

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

标签: java socketchannel


【解决方案1】:

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

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

else-if 替换为if 并查看结果。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    相关资源
    最近更新 更多