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