void handleWrite() {
        if (queue.isEmpty() && outgoing == null) {
            key.interestOps(SelectionKey.OP_READ);
            return;
        }

        try {
            if (outgoing == null) {
                Queued b = (Queued) queue.pop();
                
                ByteBuffer[] msg = b.getMsg();

                if (msg == null) {
                    return;
                }
                short port = b.getPort();
                int size = 0;

                for (int i = 0; i < msg.length; i++) {
                    size += msg[i].remaining();
                }

                ByteBuffer header = ByteBuffer.allocate(6);

                header.putInt(size);
                header.putShort(port);
                header.flip();
                outgoing = new ByteBuffer[msg.length + 1];
                outgoing[0] = header;
                System.arraycopy(msg, 0, outgoing, 1, msg.length);
                outremaining = size + 6;
            }
            
            if (outgoing != null) {
                long n = sock.write(outgoing, 0, outgoing.length);
                dirty=true;
                transport.bytesOut+=n;

                outremaining -= n;
                if (outremaining == 0) {
                	transport.pktOut++;
                    outgoing = null;
                }
                key.interestOps(SelectionKey.OP_WRITE | SelectionKey.OP_READ);
            }            
        } catch (IOException e) {
            handleClose();
        } catch (CancelledKeyException cke) {
        	// Make sure connection is closed
            transport.notifyClose(this);
        }
        
    }