我想要达到的结果
public void listen () {
SelectionKey selectionKey = null;
try {
//这里换成while (true)就不行了 不知道为啥
while (selector.select() > 0) {
//获取所有的就绪事件
Iterator selectionKeyIterator = selector.selectedKeys().iterator();
while (selectionKeyIterator.hasNext()) {
selectionKey = selectionKeyIterator.next();
//处理客户端连接请求
if (selectionKey.isAcceptable()) {
SocketChannel socketChannel = serverSocketChannel.accept();
socketChannel.configureBlocking(false);
socketChannel.register(selector, SelectionKey.OP_READ);
//处理客户端发送数据的请求(客户端 channel可读)
} else if (selectionKey.isReadable()) {
readMsgFromClient(selectionKey);
}
selectionKeyIterator.remove();
}
}
} catch (IOException ioException) {
ioException.printStackTrace();
}
}
//这里换成while (true)就不行了 不知道为啥
while (selector.select() > 0)
建议你看下这篇博客
NIO的由来,为什么需要NIO(一)