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条回答

    报告相同问题?

    悬赏问题

    • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
    • ¥15 帮我写一个c++工程
    • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
    • ¥15 关于smbclient 库的使用
    • ¥15 微信小程序协议怎么写
    • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
    • ¥20 怎么用dlib库的算法识别小麦病虫害
    • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
    • ¥15 java写代码遇到问题,求帮助
    • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?