我对java nio感到很困惑,
package org.eclipse.java.nio.selector.test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
public class MySelector {
public static void main(String[] args) throws IOException {
// Create selector
Selector selector = null;
selector = Selector.open();
////////////////////////////////////////////////////////////////////////
SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress(
"localhost", 4321));
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
/*
* Let's begin select
*/
while (true) {
int readyChannels = selector.select();
if (readyChannels == 0) continue;
System.out.println("Hello, selector!");
Set readyKeys = selector.selectedKeys();
Iterator it = readyKeys.iterator();
while (it.hasNext()) {
SelectionKey key = (SelectionKey )it.next();
if (key.isReadable()) {
System.out.println("It's readable!");
}
it.remove();
}
}
}
}
我希望选择器等待来自远程服务器的下一个输入事件,但它在服务器回复任何单词后陷入无限循环,为什么? 我真的无法理解,'删除'不起作用? 我不想取消或关闭频道,我想保持连接,让客户端等待服务器的回复......
答案 0 :(得分:2)
必须在isReadable判断块中执行读取。 如果您不执行读取从可读通道传输的数据, 再次选择频道。所以while循环不会停止。
while (it.hasNext()) {
SelectionKey key = (SelectionKey )it.next();
if (key.isReadable()) {
System.out.println("It's readable!");
// Added read operation
ByteBuffer buffer = ByteBuffer.allocate(1024);
Charset charset = Charset.forName("UTF-8");
buffer.clear();
if (socketChannel.read(buffer) < 0) {
// Client connection refused
socketChannel.close();
return;
}
buffer.flip();
System.out.println("Value = " + charset.decode(buffer).toString());
}
it.remove();
}
我认为“删除”有效。 “你好,读取选择器!”可能会重复输出。