服务端代码:
public static void main(String[] args) throws Exception
{
// 创建选择器
Selector selector = Selector.open();
// 打开监听信道
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 与本地端口绑定
serverSocketChannel.socket().bind(new InetSocketAddress(9999));
// 设置为非阻塞模式
serverSocketChannel.configureBlocking(false);
// 将选择器绑定到监听信道,只有非阻塞信道才可以注册选择器.并在注册过程中指出该信道可以进行Accept操作
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
while (true)
{
// 等待某信道就绪
int selectInt = selector.select();
if (selectInt == 0)
continue;
// 取得迭代器.selectedKeys()中包含了每个准备好某一I/O操作的信道的SelectionKey
Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
while (iterator.hasNext())
{
SelectionKey selectionKey = iterator.next();
// 有客户端连接请求时
if (selectionKey.isAcceptable())
handleAccept(selectionKey);
// 从客户端读取