(2008-02-25 20:34:58)   JAVA<[email protected]>
public static void SdoWork(String msg)
throws Exception
{
System.out.println("Enter SdoWork bbb");
System.out.println("--------------1----------------");
try
{
Iterator it = selector.keys().iterator();
int a = selector.keys().size();
  System.out.println(a);
System.out.println(msg);

while (it.hasNext()) 
{
SelectionKey key = (SelectionKey)it.next();
System.out.println("--------------2----------------");
if (key.isValid() && key.interestOps() != 16)
{
SocketChannel socketChannel = (SocketChannel)key.channel();
buffer.clear();
buffer.put(msg.getBytes());
buffer.flip();
socketChannel.write(buffer);
System.out.println("--------------3----------------");
}
key = null;

}
}
catch (Exception ex)
{
ex.printStackTrace();
CloseAllConnect();
}
}
这段代码有时会有错误,,java.nio.channels.ClosedSelectorException
        at sun.nio.ch.SelectorImpl.keys 请指点一下,  
下面的是CloseAllConnect();
public static void CloseAllConnect()
{
System.out.println("Enter CloseAllConnect");
SendClientDate.SetStr();
try
{
Iterator it = selector.keys().iterator();
int a = selector.keys().size();
if (a < 1)
return;
while (it.hasNext()) 
{
SelectionKey key = (SelectionKey)it.next();
if (key.isValid() && key.interestOps() != 16)
{
SocketChannel socketChannel = (SocketChannel)key.channel();
socketChannel.close();
}
key.cancel();
key = null;
}
serverChannel.socket().close();
serverChannel.close();
serverSocket.close();
selector.close();
}
catch (Exception ex)
{
System.out.println(ex.toString());
}
}

解决方案 »

  1.   

    这段代码有时会有错误,, java.nio.channels.ClosedSelectorException 
            at sun.nio.ch.SelectorImpl.keys  
      

  2.   

    java.nio.channels.ClosedSelectorException  :试图在已关闭的选择器上调用 I/O 操作时抛出的未经检查的异常。
    在你调用closeAllConnect()方法中
    while (it.hasNext())  

    SelectionKey key = (SelectionKey)it.next(); 

    这个地方可能出错了。还有,把报错的详细信息贴上,不然只有神仙才知道是啥原因。