public class MultiReactorNioServer {
private static final ExecutorService exePool = Executors.newFixedThreadPool(4);
public static void main(String[] args) throws Exception{
//定义俩个selector监听器
//一个负责Accept的监听,一个负责客户端channel上的读写事件的监听
Selector acceptSelector = Selector.open();
final Selector ioEventSelector = Selector.open();
ServerSocketChannel server = ServerSocketChannel.open();
server.configureBlocking(false);
server.bind(new InetSocketAddress("localhost",8585));
server.register(acceptSelector, SelectionKey.OP_ACCEPT);
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try{
while (true){
ioEventSelector.select();
Set<SelectionKey> keys = ioEventSelector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
//如果是客户端上的读事件
if(key.isReadable()){
exePool.submit(new Runnable() {
@Override
public void run() {
//执行IO读操作
}
});
}
iterator.remove(); //移除处理过的事件
}
}
}catch (Exception e){
e.printStackTrace();
}
}
});
t.start();
while (true){
acceptSelector.select();
//SocketChannel accept = server.accept(); 为什么不需要掉accept
Set<SelectionKey> keys = acceptSelector.selectedKeys();
Iterator<SelectionKey> iterator = keys.iterator();
while (iterator.hasNext()){
SelectionKey key = iterator.next();
if(key.isAcceptable()){
SocketChannel clientChannel = (SocketChannel) key.channel();
clientChannel.configureBlocking(false);
//使用|或运算符,注册多个事件
clientChannel.register(ioEventSelector,SelectionKey.OP_READ | SelectionKey.OP_WRITE);
}
//事件处理完后,要把事件从待处理事件中移出
iterator.remove();
}
}
}
}
网友评论