selector
channel触发的事件,selector必须处理,可以通过cancel取消待处理的事件,也可以通过channel相应的方法去处理待处理的事件。无论怎么样,事件必须得到处理,否则
selector.select();
始终会检测到待处理的事件,无法达到阻塞状态。
不处理事件
server
package com.hello.netty;
import lombok.extern.slf4j.Slf4j;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;
@Slf4j
public class Server {
public static void main(String[] args) throws IOException {
// 1. 创建 selector 管理多个channel
Selector selector = Selector.open();
ServerSocketChannel ssc = ServerSocketChannel.open();
ssc.configureBlocking(false);
// 2. 建立 selector 和 channel 的联系(channel注册到selector)
// SelectionKey 中包含了 selector 和 注册的 channel的信息.
SelectionKey sscKey = ssc.register(selector, 0, null);
// sscKey 只关注 accept事件
sscKey.interestOps(SelectionKey.OP_ACCEPT);
log.debug("register key: {}",sscKey);
ssc.bind(new InetSocketAddress(8080));
while(true){
// 3. select方法,没有事件发生时,线程阻塞,有事件发生时继续运行.
selector.select();
// 4. 处理事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey key = iterator.next();
log.debug("key: {}",key);
// ServerSocketChannel channel = (ServerSocketChannel)key.channel();
// SocketChannel sc = channel.accept();
// log.debug("SocketChannel: {}",sc);
}
}
}
}
client
package com.hello.netty;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;
public class Client {
public static void main(String[] args) throws IOException {
SocketChannel sc = SocketChannel.open();
sc.connect(new InetSocketAddress("localhost",8080));
System.out.println("waiting...");
}
}
启动server后,再启动client,ServerSocketChannel触发的accept事件,如果不处理该事件,selector.select();
检测始终有新事件待处理,无法达到阻塞状态。
10:09:08.407 [main] DEBUG com.hello.netty.Server - key: sun.nio.ch.SelectionKeyImpl@2b71fc7e
10:09:08.407 [main] DEBUG com.hello.netty.Server - key: sun.nio.ch.SelectionKeyImpl@2b71fc7e
10:09:08.407 [main] DEBUG com.hello.netty.Server - key: sun.nio.ch.SelectionKeyImpl@2b71fc7e
10:09:08.407 [main] DEBUG com.hello.netty.Server - key: sun.nio.ch.SelectionKeyImpl@2b71fc7e
10:09:08.407 [main] DEBUG com.hello.netty.Server - key: sun.nio.ch.SelectionKeyImpl@2b71fc7e
10:09:08.407 [main] DEBUG com.hello.netty.Server - key: sun.nio.ch.SelectionKeyImpl@2b71fc7e
cancel取消事件
对于未处理的事件,也可以通过SelectionKey#cancel方法取消事件。
while(true){
// 3. select方法,没有事件发生时,线程阻塞,有事件发生时继续运行.
selector.select();
// 4. 处理事件
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while(iterator.hasNext()){
SelectionKey key = iterator.next();
log.debug("key: {}",key);
//ServerSocketChannel channel = (ServerSocketChannel)key.channel();
//SocketChannel sc = channel.accept();
//log.debug("SocketChannel: {}",sc);
key.cancel();
}
}
总结
selector.select();
存在事件未处理时,不会阻塞,事件发生后要么处理,要么取消,不能置之不理。