日期:2014-05-20  浏览次数:20817 次

java nio 问题
问题描述如下:
鄙人在写nio简单例子的时候出现了很奇怪的问题,服务器端部分代码如下:

while (selector.select() > 0) 
{
  Set<SelectionKey> readyKeys = selector.selectedKeys();
   Iterator it = readyKeys.iterator();
   System.out.println("while out");
   while (it.hasNext()) 
   {
      System.out.println("while in");
      SelectionKey key = (SelectionKey) it.next();
      it.remove();
      if (key.isAcceptable()) 
{
   System.out.println("Key is Acceptable");
   socket = (SocketChannel) ssc.accept();
   socket.configureBlocking(false);
   socket.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE);
}
if (key.isReadable()) {

    System.out.println("Key is readable");
    socket = (SocketChannel) key.channel();
    ByteBuffer buf = ByteBuffer.allocate(25);
    buf.clear();
    socket.read(buf);
    buf.flip();
    Charset charset = Charset.forName("us-ascii");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buf);
    String result = charBuffer.toString();
    System.out.println("Receive Data:" + result);
   // key.cancel();如果这个注释的话,就会进行无限循环
}

}


客户端发送代码:为

public static int sendMessage(SocketChannel client) {
String msg = null;
ByteBuffer bytebuf=ByteBuffer.allocate(1024);
int nBytes = 0;
try {
msg = "It's message from client!";
System.out.println("msg is "+msg);


bytebuf.clear();
bytebuf.put(msg.getBytes());
bytebuf.flip();
nBytes = client.write(bytebuf);
System.out.println("It's message from client!".getBytes().length);


client.close();

} catch (IOException e) {
e.printStackTrace();
}
return nBytes;
 }


客户端和服务器端的部分代码就是上面的,客户端发送数据给服务器端,服务器按道理执行了
SelectionKey key = (SelectionKey) it.next();
it.remove();的代码之后注销了该键,如果执行完读操作之后,只要加上key.cancel()之后才可以正常读取一条数据。it.remove()之后为什么selector.select() > 0依然成立,运行代码的打印结果:
while out
while in
Key is readable
Receive Data:
while out
while in
Key is readable
Receive Data:
while out
while in
Key is readable
Receive Data:。。。。。
求高手解答。

------解决方案--------------------
这个就是这样的,具体原因我也没研究过
------解决方案--------------------
http://bbs.csdn.net/topics/390351293
已回复。
------解决方案--------------------
哪里有selector.select() > 0 ?

虽然remove了,但是貌似key引用还在,不cancel是会继续运行