while (true) {
// 选择一组键
selector.select();
// 返回此选择器的已选择键集
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
// 遍历对应的 SelectionKey 处理
while (iterator.hasNext()) {
SelectionKey selectionKey = (SelectionKey) iterator.next();
iterator.remove();
if(!selectionKey.isValid()){
continue;
}
// 判断此键的通道是否已完成其套接字连接操作
if (selectionKey.isConnectable()) {
connected(selectionKey);
}
// 判断是否连接可读操作
else if (selectionKey.isReadable()) {
readMessage(selectionKey);
}
// 判断是否连接可写操作
else if (selectionKey.isWritable()) {
writeMessage(selectionKey);
}
}
selectionKeys.clear();
}
private void connected(SelectionKey selectionKey) throws IOException {
SocketChannel client = (SocketChannel) selectionKey.channel();
// 判断该通道是否进行连接过程、完成连接过程
if (client.isConnectionPending()) {
if (client.finishConnect()) {
client.write("hello"); // 将数据写入该通道
client.register(selector, SelectionKey.OP_READ);
}
}
}
代码如上,为什么每次,执行connected(SelectionKey selectionKey) 过后循环到selector.select();后就一直等待?