Search code examples
javaiteratorniosocketchannel

Java NIO Exception


Hi I am trying to make a chat using NIO, in the server part in a separate thread from the main when I :

private void broadcast(String msg, String user)    
{
    String Message = user + ":" + msg + "\0";
    System.out.println(Message);
    ByteBuffer buf=ByteBuffer.wrap(Message.getBytes());
    Set<SelectionKey> selectedKeys  = selector.keys();
    Iterator<SelectionKey> keyIterator = selectedKeys.iterator();

    while(keyIterator.hasNext()) 
    {
        SelectionKey key = keyIterator.next();
        if(key.attachment() != user)
        {
            try {
                ((SocketChannel) key.channel()).write(buf);
            } catch (IOException e) {
                e.printStackTrace();
            }
            buf.rewind();
        }
        keyIterator.remove();
    }
}

I get this exception:

java.lang.UnsupportedOperationException
at java.util.Collections$UnmodifiableCollection$1.remove(Unknown Source)
at chatserver.MessageSender.broadcast(MessageSender.java:41)
at chatserver.MessageSender.run(MessageSender.java:113)
at java.lang.Thread.run(Unknown Source)

Line 41 is: keyIterator.remove(); I am using this as guideline: Java NIO Tutorial


Solution

  • You are invoking Selector.keys() where you appear to want Selector.selectedKeys(). The Set returned by the former is documented to be completely unmodifiable, whereas the one returned by the latter -- which agrees better with the name of the variable to which you assign the result -- is documented to permit element removal. Moreover, the selected keys are the ones ready for I/O.