private void processSelectedKeys() throws IOException
    {
        Set<SelectionKey> selectedKeys = _selector.selectedKeys();
        Iterator<SelectionKey> iter = selectedKeys.iterator();
        while (iter.hasNext())
        {
            final SelectionKey key = iter.next();
            if (key.isValid())
            {
                try
                {
                    if (key.isAcceptable())
                    {
                        handleAccept(key);
                    }

                    if (key.isConnectable())
                    {
                        handleConnect(key);
                    }

                    if (key.isReadable())
                    {
                        read(key);
                    }

                    if (key.isWritable())
                    {
                        write(key);
                    }
                }
                catch (CancelledKeyException | IOException e)
                {
                    Agent agent = (Agent) key.attachment();
                    if (key.channel() instanceof SocketChannel)
                    {
                        final SocketChannel channel = (SocketChannel) key.channel();
                        closeNow(channel.socket());
                        key.cancel(); //idempotent
                        notifyAgentSocketChannelClosed(channel.socket(), agent);
                    }
                    else if (key.channel() instanceof ServerSocketChannel)
                    {
                        _logger.error("exception in server socket channel", e);
                        ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel();
                        serverSocketChannel.socket().close();
                        notifyAgentServerSocketChannelClosed(agent);
                    }
                }
            }
            iter.remove();
        }
    }