Example usage for java.nio.channels SelectionKey attachment

List of usage examples for java.nio.channels SelectionKey attachment

Introduction

In this page you can find the example usage for java.nio.channels SelectionKey attachment.

Prototype

Object attachment

To view the source code for java.nio.channels SelectionKey attachment.

Click Source Link

Usage

From source file:ca.wumbo.doommanager.server.ServerManager.java

/**
 * Kills any connections that have not sent any messages for a period of
 * time./*  w  w w. ja v  a 2s. c  om*/
 * 
 * @return
 *       True if there was no error, false if an error occured.
 */
private boolean killInactiveConnections() {
    // Go through each connection every so often to check for dead connections.
    if (System.currentTimeMillis() - lastTimeoutCheckMillis > TIMEOUT_FREQUENCY_CHECK_MILLIS) {
        lastTimeoutCheckMillis = System.currentTimeMillis();
        log.trace("Checking for timeouts... {}", System.currentTimeMillis());

        // We cannot do this if the selector is closed.
        if (selector.isOpen()) {
            // Go through each connection...
            for (SelectionKey key : selector.keys()) {
                // If the attachment has client info (which it always should)...
                if (key.attachment() instanceof ClientInfo) {
                    ClientInfo clientInfo = (ClientInfo) key.attachment();
                    // If the client hasn't responded for a certain amount of time, kill the connection.
                    if (clientInfo.hasReceivedMessageSince(TIMEOUT_CLIENT_MILLIS)) {
                        log.info("Client {} timed out, requesting connection termination.",
                                clientInfo.getIPAddress());
                        Channel channel = key.channel();
                        key.cancel();
                        try {
                            channel.close();
                        } catch (IOException e) {
                            log.error("Error closing a timed out client's channel: {}", e.getMessage());
                        }
                    }
                }
            }
        }
    }

    // Signal all is good.
    return true;
}

From source file:edu.tsinghua.lumaqq.qq.net.Porter.java

/**
 * ??IPort./*from w w w .j  a  va2s.  co m*/
 * ???//.
 * @see IPort#send(ByteBuffer)
 * @see IPort#receive(ByteBuffer)
 * @see IPort#maintain()
 */
@Override
public void run() {
    log.debug("Porter??");
    int n = 0;
    while (!shutdown) {
        // do select
        try {
            n = selector.select(3000);
            // ?shutdownselector
            if (shutdown) {
                selector.close();
                break;
            }
        } catch (IOException e) {
            log.error(e.getMessage());
            dispatchErrorToAll(e);
        }

        // ?
        processDisposeQueue();

        // select0?
        if (n > 0) {
            for (Iterator<SelectionKey> i = selector.selectedKeys().iterator(); i.hasNext();) {
                // Key
                SelectionKey sk = i.next();
                i.remove();
                // ?
                if (!sk.isValid())
                    continue;

                // ?
                INIOHandler handler = (INIOHandler) sk.attachment();
                try {
                    if (sk.isConnectable())
                        handler.processConnect(sk);
                    else if (sk.isReadable())
                        handler.processRead(sk);
                } catch (IOException e) {
                    log.error(e.getMessage());
                    handler.processError(e);
                } catch (PacketParseException e) {
                    log.debug("?: " + e.getMessage());
                } catch (RuntimeException e) {
                    log.error(e.getMessage());
                }
            }

            n = 0;
        }

        checkNewConnection();
        notifySend();
    }

    selector = null;
    shutdown = false;
    log.debug("Porter?");
}

From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java

private final Session getSessionFromAttchment(final SelectionKey key) {
    if (key.attachment() instanceof Session) {
        return (Session) key.attachment();
    }//from w w  w  . java  2s  .c o  m
    return null;
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private void writePacket(SelectionKey key) {
    @SuppressWarnings("unchecked")
    T con = (T) key.attachment();

    int wrotePackets = 0;
    int wroteBytes = 0;

    for (;;) {//  w w  w  .j  ava2s . c  om
        wrotePackets += prepareWriteBuffer2(con, wrotePackets, wroteBytes);
        wroteBytes += getDirectWriteBuffer().position();
        getDirectWriteBuffer().flip();

        int size = getDirectWriteBuffer().remaining();

        int result = -1;

        try {
            result = con.getWritableChannel().write(getDirectWriteBuffer());
        } catch (IOException e) {
            // error handling goes on the if bellow
        }

        // check if no error happened
        if (result >= 0) {
            // check if we wrote everything
            if (result == size) {
                // complete write
                synchronized (con) {
                    if (con.getSendQueue2().isEmpty() && !con.hasPendingWriteBuffer()) {
                        con.disableWriteInterest();
                        return;
                    } else if (wrotePackets >= getMaxOutgoingPacketsPerPass()
                            || wroteBytes >= getMaxOutgoingBytesPerPass())
                        return;
                }
            } else
            // incomplete write
            {
                con.createWriteBuffer(getDirectWriteBuffer());
                return;
            }
        } else {
            closeConnectionImpl(con, true);
            return;
        }
    }
}

From source file:com.byteatebit.nbserver.simple.SelectorTask.java

@Override
public SelectionKey register(SelectableChannel channel, int ops, IOTask nioTask, IOTimeoutTask timeoutTask,
        long timeoutMs) {
    Preconditions.checkNotNull(channel, "channel cannot be null");
    Preconditions.checkNotNull(nioTask, "nioTask cannot be null");
    IOTimeoutTask ioTimeoutTask = timeoutTask == null ? defaultIoTimeoutTask : timeoutTask;
    if (LOG.isDebugEnabled())
        LOG.debug("registering channel " + channel + "for ops " + ops + " and task " + nioTask);
    SelectionKey key = null;
    NioSelectionKeyEntry selectionKeyEntry = null;
    synchronized (this) {
        try {/*w  w w .  ja v a 2 s. c  o  m*/
            key = channel.keyFor(selector);
            if (key != null) {
                key.interestOps(key.interestOps() | ops);
                selectionKeyEntry = (NioSelectionKeyEntry) key.attachment();
            } else {
                selectionKeyEntry = new NioSelectionKeyEntry();
                key = channel.register(selector, ops, selectionKeyEntry);
            }
        } catch (ClosedChannelException e) {
            throw new SelectorException(e);
        }
        selectionKeyEntry.setTask(nioTask, ioTimeoutTask, ops, timeoutMs);
    }
    if (LOG.isDebugEnabled())
        LOG.debug("Total number of selection keys: " + selector.keys().size());
    return key;
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private void readPacket(SelectionKey key) {
    @SuppressWarnings("unchecked")
    T con = (T) key.attachment();

    ByteBuffer buf = con.getReadBuffer();

    if (buf == null) {
        buf = getReadBuffer();/*from   www.ja v  a2s. co  m*/
        buf.clear();
    }

    int readPackets = 0;
    int readBytes = 0;

    for (;;) {
        final int remainingFreeSpace = buf.remaining();
        int result = -2;

        try {
            result = con.getReadableByteChannel().read(buf);
        } catch (IOException e) {
            //error handling goes bellow
        }

        switch (result) {
        case -2: // IOException
        {
            closeConnectionImpl(con, true);
            return;
        }
        case -1: // EOS
        {
            closeConnectionImpl(con, false);
            return;
        }
        default: {
            buf.flip();
            // try to read as many packets as possible
            for (;;) {
                final int startPos = buf.position();

                if (readPackets >= getMaxIncomingPacketsPerPass() || readBytes >= getMaxIncomingBytesPerPass())
                    break;

                if (!tryReadPacket2(con, buf))
                    break;

                readPackets++;
                readBytes += (buf.position() - startPos);
            }
            break;
        }
        }

        // stop reading, if we have reached a config limit
        if (readPackets >= getMaxIncomingPacketsPerPass() || readBytes >= getMaxIncomingBytesPerPass())
            break;

        // if the buffer wasn't filled completely, we should stop trying as the input channel is empty
        if (remainingFreeSpace > result)
            break;

        // compact the buffer for reusing the remaining bytes
        if (buf.hasRemaining())
            buf.compact();
        else
            buf.clear();
    }

    // check if there are some more bytes in buffer and allocate/compact to prevent content lose.
    if (buf.hasRemaining()) {
        if (buf == getReadBuffer()) {
            con.setReadBuffer(getPooledBuffer().put(getReadBuffer()));
        } else {
            buf.compact();
        }
    } else {
        if (buf == getReadBuffer()) {
            // no additional buffers used
        } else {
            con.setReadBuffer(null);
            recycleBuffer(buf);
        }
    }
}

From source file:com.springrts.springls.ServerThread.java

/** Check for incoming messages */
private void readIncomingMessages() {

    Client client = null;/*  www .  j  av  a 2  s. c  om*/
    try {
        // non-blocking select, returns immediately regardless of
        // how many keys are ready
        readSelector.selectNow();

        // fetch the keys
        Set<SelectionKey> readyKeys = readSelector.selectedKeys();

        // run through the keys and process each one
        while (!readyKeys.isEmpty()) {
            SelectionKey key = readyKeys.iterator().next();
            readyKeys.remove(key);
            SocketChannel channel = (SocketChannel) key.channel();
            client = (Client) key.attachment();
            if (client.isHalfDead()) {
                continue;
            }
            readBuffer.clear();

            client.setTimeOfLastReceive(System.currentTimeMillis());

            // read from the channel into our buffer
            long nBytes = channel.read(readBuffer);
            client.addReceived(nBytes);

            // basic anti-flood protection
            FloodProtectionService floodProtection = getContext().getService(FloodProtectionService.class);
            if ((floodProtection != null) && floodProtection.isFlooding(client)) {
                continue;
            }

            // check for end-of-stream
            if (nBytes == -1) {
                LOG.debug("Socket disconnected - killing client");
                channel.close();
                // this will also close the socket channel
                getContext().getClients().killClient(client);
            } else {
                // use a CharsetDecoder to turn those bytes into a string
                // and append it to the client's StringBuilder
                readBuffer.flip();
                String str = getContext().getServer().getAsciiDecoder().decode(readBuffer).toString();
                readBuffer.clear();
                client.appendToRecvBuf(str);

                // TODO move this to Client#appendToRecvBuf(String)
                // check for a full line
                String line = client.readLine();
                while (line != null) {
                    executeCommandWrapper(line, client);

                    if (!client.isAlive()) {
                        // in case the client was killed within the
                        // executeCommand() method
                        break;
                    }
                    line = client.readLine();
                }
            }
        }
    } catch (IOException ioex) {
        LOG.info("exception during select(): possibly due to force disconnect. Killing the client ...");
        if (client != null) {
            getContext().getClients().killClient(client, "Quit: connection lost");
        }
        LOG.debug("... the exception was:", ioex);
    }
}

From source file:com.l2jfree.network.mmocore.ReadWriteThread.java

private void finishConnection(SelectionKey key) {
    try {// w  ww  .  j a  va 2  s  . com
        ((SocketChannel) key.channel()).finishConnect();
    } catch (IOException e) {
        @SuppressWarnings("unchecked")
        T con = (T) key.attachment();
        closeConnectionImpl(con, true);
        return;
    }

    // key might have been invalidated on finishConnect()
    if (key.isValid()) {
        key.interestOps(key.interestOps() | SelectionKey.OP_READ);
        key.interestOps(key.interestOps() & ~SelectionKey.OP_CONNECT);
    }
}

From source file:com.taobao.gecko.core.nio.impl.Reactor.java

private final long checkSessionTimeout() {
    long nextTimeout = 0;
    if (this.configuration.getCheckSessionTimeoutInterval() > 0) {
        this.gate.lock();
        try {//from   w  w  w .j a  v a2s  .  c  om
            if (this.selectTries * 1000 >= this.configuration.getCheckSessionTimeoutInterval()) {
                nextTimeout = this.configuration.getCheckSessionTimeoutInterval();
                for (final SelectionKey key : this.selector.keys()) {
                    // expiredidle
                    if (key.attachment() != null) {
                        final long n = this.checkExpiredIdle(key, this.getSessionFromAttchment(key));
                        nextTimeout = n < nextTimeout ? n : nextTimeout;
                    }
                }
                this.selectTries = 0;
            }
        } finally {
            this.gate.unlock();
        }
    }
    return nextTimeout;
}

From source file:com.alibaba.napoli.gecko.core.nio.impl.Reactor.java

private final long checkSessionTimeout() {
    long nextTimeout = 0;
    if (this.configuration.getCheckSessionTimeoutInterval() > 0) {
        this.gate.lock();
        try {//from   w  ww  .j av a 2 s .  c  om
            if (this.selectTries * 1000 >= this.configuration.getCheckSessionTimeoutInterval()) {
                nextTimeout = this.configuration.getCheckSessionTimeoutInterval();
                for (final SelectionKey key : this.selector.keys()) {
                    // ?expiredidle
                    if (key.attachment() != null) {
                        final long n = this.checkExpiredIdle(key, this.getSessionFromAttchment(key));
                        nextTimeout = n < nextTimeout ? n : nextTimeout;
                    }
                }
                this.selectTries = 0;
            }
        } finally {
            this.gate.unlock();
        }
    }
    return nextTimeout;
}