woyaodangti 2016-05-04 13:05
浏览 654

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了啊 即使有新的连接进入 不太懂这个原理 麻烦又大神能讲下吗 万分感谢

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥100 c语言,请帮蒟蒻看一个题
    • ¥15 名为“Product”的列已属于此 DataTable
    • ¥15 安卓adb backup备份应用数据失败
    • ¥15 eclipse运行项目时遇到的问题
    • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
    • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
    • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
    • ¥50 成都蓉城足球俱乐部小程序抢票
    • ¥15 yolov7训练自己的数据集
    • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)