temp

for (; ; ){ selector.select(); //阻塞等待事件的到来,这里就是一个监听器,事件来了,就往下执行 Iterator iter = selector.selectedKeys().iterator(); while (iter.hasNext()) { SelectionKey key = (SelectionKey) iter.next(); iter.remove(); process(key); //调用事件处理器 } {color:#000000}} // 处理事件 (作为demo,此处直接在单线程内处理一切事情,实际上像netty,是将process的处理过程,扔给worker线程池完成。refer) protected void process(SelectionKey key) throws IOException { if (key.isAcceptable()) { // 接收请求 ServerSocketChannel server = (ServerSocketChannel) key.channel(); SocketChannel channel = server.accept(); //设置非阻塞模式 channel.configureBlocking(false); channel.register(selector, SelectionKey.OP_READ); } else if (key.isReadable()) { // 读信息 SocketChannel channel = (SocketChannel) key.channel(); int count = channel.read(clientBuffer); if (count > 0) { clientBuffer.flip(); CharBuffer charBuffer = decoder.decode(clientBuffer); name = charBuffer.toString(); // System.out.println(name); SelectionKey sKey = channel.register(selector, SelectionKey.OP_WRITE); sKey.attach(name); } else { channel.close(); } clientBuffer.clear(); } else if (key.isWritable()) { // 写事件 SocketChannel channel = (SocketChannel) key.channel(); String name = (String) key.attachment(); ByteBuffer block = encoder.encode(CharBuffer .wrap("Hello !" + name)); channel.write(block); //channel.close(); }

你可能感兴趣的:(iterator,string,server)