【发布时间】: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