- 利用NIO编程知识,实现多人聊天室 ```java package io.torey.niotest;
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.util.Iterator; import java.util.Set;
/**
NIO服务器端 */ public class NioServer { public static void main(String[] args){
NioServer nioServer = new NioServer();
}
/**
- 启动 */ public void start() throws IOException{ //1 创建Selector //2 通过ServerSocketChannel创建channel通道 //3 为channel通道绑定监听端口 //4 重点:设置channel为非阻塞模式 //5 将channel注册到selector上,监听连接事件 //6 循环等待新接入的连接 //7 根据就绪状态,调用对应方法处理业务逻辑
//1 创建SelectorSelector selector = Selector.open();//2 通过ServerSocketChannel创建channel通道ServerSocketChannel serverSocketChannel= ServerSocketChannel.open();//3 为channel通道绑定监听端口serverSocketChannel.bind(new InetSocketAddress(8000));//4 重点:设置channel为非阻塞模式serverSocketChannel.configureBlocking(false);//5 将channel注册到selector上,监听连接事件serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);System.out.println("服务器启动成功!!");//6 循环等待新接入的连接while (true) {//这个方法是阻塞方法,获取可用的channel数量int readyChannels= selector.select();if (readyChannels==0) {continue;}//获取可用channel的集合Set<SelectionKey> selectionKeys = selector.selectedKeys();Iterator<SelectionKey> iterator = selectionKeys.iterator();while (iterator.hasNext()) {//selectionKey的实例SelectionKey selectionKey = iterator.next();//移除Set中当前的selectionKey,重点iterator.remove();//7 根据就绪状态,调用对应方法处理业务逻辑//如果是 接入事件//如果是 可读事件}}}
}
```
