2 woyaodangti woyaodangti 于 2016.05.04 21:05 提问

NIO 不调用iterator的remove的问题

package chatIO;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.util.Iterator;

public class chatServiceNIO {

private static final int BUFSIZE = 256; // Buffer size (bytes)
private static final int TIMEOUT = 3000; // Wait timeout (milliseconds)

public static void main(String[] args) throws IOException {
    Selector selector = Selector.open();

    ServerSocketChannel listnChannel = ServerSocketChannel.open();
    listnChannel.socket().bind(new InetSocketAddress(9090));
    listnChannel.configureBlocking(false); // must be nonblocking to
                                            // register
    listnChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
        if (selector.select(TIMEOUT) == 0) { // returns # of ready chans
            System.out.print(".");
            continue;
        }

        Iterator<SelectionKey> keyIter = selector.selectedKeys().iterator();
        while (keyIter.hasNext()) {
            SelectionKey key = keyIter.next(); // Key is bit mask
            if (key.isAcceptable()) {
                System.out.println("accept....");
                SocketChannel sc = ((ServerSocketChannel) key.channel()).accept();
                sc.configureBlocking(false);
                sc.register(selector, SelectionKey.OP_READ);
            }
            if (key.isReadable()) {
                SocketChannel sc = (SocketChannel) key.channel();
                ByteBuffer bb = ByteBuffer.allocate(300);
                sc.read(bb);
                bb.flip();
                System.out.println(Charset.forName("UTF-8").decode(bb));

            }
            //keyIter.remove(); // remove from set of selected keys
        }
    }
}

}


这里我把iterator的remove注释了 为什么select()方法就一直返回0了啊 即使有新的连接进入 不太懂这个原理 麻烦又大神能讲下吗 万分感谢

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!