public void talk()throws IOException
{
datagramChannel.register(selector , SelectionKey.OP_READ | SelectionKey.OP_WRITE) ;
while(selector.select() > 0)
{
Set readyKeys = selector.selectedKeys() ;
Iterator it = readyKeys.iterator() ;
while(it.hasNext())
{
SelectionKey key = null ;
try
{
key = (SelectionKey) it.next() ;
//为什么要进行这一步??
it.remove() ;
if(key.isReadable())
receive(key) ;
if(key.isWritable())
send(key) ;
}
catch (IOException e)
{
e.printStackTrace() ;
try
{
if(key != null)
{
key.cancel() ;
key.channel().close() ;
}
}
catch (Exception ex)
{
ex.printStackTrace() ;
}
}
}
}
}
为什么在每次获取到Selectionkey
后都要用迭代器在集合中删除掉这一项呢?
以我不知道底层的理解:这是个消息,处理的时候肯定要remove掉,不然重复处理毫无意义