//1.创建selector
Selector selector = Selector.open();
//2.通过serverSocketChannel创建channel
ServerSocketChannel channel = ServerSocketChannel.open();
//3.为channel通道绑定监听端口
channel.bind(new InetSocketAddress(8000));
//4.设置channel为非阻塞模式
channel.configureBlocking(false);
//5.将channel注册到selector上,监听连接事件
channel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务器启动");
//6.调用selectKeys方法获取就绪channel集合
//7.判断就绪事件种类,调用业务处理方法
// 8.根据业务需要决定是否再次注册监听事件,重复执行第三步操作。
//循环等待新接入的连接
for(;;){
int select = selector.select();
if(select==0){
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey selectionKey = iterator.next();
//移除set中的当期selectionKey
iterator.remove();
//分状态进行处理
if(selectionKey.isAcceptable()){
acceptHandler(channel,selector);
}
//处理可读
if(selectionKey.isReadable()){
readHandler(selectionKey,selector);
}
}
}
NIO编程实现
最新推荐文章于 2024-04-20 21:50:40 发布