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:MainClass.java

public static void main(String[] args) throws IOException {
    for (int i = 0; i < data.length; i++)
        data[i] = (byte) i;

    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);//from  w w  w.j  av a2s  .  c  om

    server.socket().bind(new InetSocketAddress(9000));
    Selector selector = Selector.open();
    server.register(selector, SelectionKey.OP_ACCEPT);

    while (true) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator iterator = readyKeys.iterator();
        while (iterator.hasNext()) {
            SelectionKey key = (SelectionKey) iterator.next();
            iterator.remove();
            if (key.isAcceptable()) {
                SocketChannel client = server.accept();
                System.out.println("Accepted connection from " + client);
                client.configureBlocking(false);
                ByteBuffer source = ByteBuffer.wrap(data);
                SelectionKey key2 = client.register(selector, SelectionKey.OP_WRITE);
                key2.attach(source);
            } else if (key.isWritable()) {
                SocketChannel client = (SocketChannel) key.channel();
                ByteBuffer output = (ByteBuffer) key.attachment();
                if (!output.hasRemaining()) {
                    output.rewind();
                }
                client.write(output);
            }
            key.channel().close();
        }
    }
}

From source file:MainClass.java

public static void main(String[] args) throws IOException {
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetEncoder encoder = charset.newEncoder();
    CharsetDecoder decoder = charset.newDecoder();

    ByteBuffer buffer = ByteBuffer.allocate(512);

    Selector selector = Selector.open();

    ServerSocketChannel server = ServerSocketChannel.open();
    server.socket().bind(new java.net.InetSocketAddress(8000));
    server.configureBlocking(false);//from ww w  .j  av  a2  s  .c om
    SelectionKey serverkey = server.register(selector, SelectionKey.OP_ACCEPT);

    for (;;) {
        selector.select();
        Set keys = selector.selectedKeys();

        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove();

            if (key == serverkey) {
                if (key.isAcceptable()) {
                    SocketChannel client = server.accept();
                    client.configureBlocking(false);
                    SelectionKey clientkey = client.register(selector, SelectionKey.OP_READ);
                    clientkey.attach(new Integer(0));
                }
            } else {
                SocketChannel client = (SocketChannel) key.channel();
                if (!key.isReadable())
                    continue;
                int bytesread = client.read(buffer);
                if (bytesread == -1) {
                    key.cancel();
                    client.close();
                    continue;
                }
                buffer.flip();
                String request = decoder.decode(buffer).toString();
                buffer.clear();
                if (request.trim().equals("quit")) {
                    client.write(encoder.encode(CharBuffer.wrap("Bye.")));
                    key.cancel();
                    client.close();
                } else {
                    int num = ((Integer) key.attachment()).intValue();
                    String response = num + ": " + request.toUpperCase();
                    client.write(encoder.encode(CharBuffer.wrap(response)));
                    key.attach(new Integer(num + 1));
                }
            }
        }
    }
}

From source file:gridool.communication.transport.nio.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();//from   www.  ja v  a 2 s  .  c  o m
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isInfoEnabled()) {
                        LOG.info("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:net.sf.cindy.impl.SimpleEventGenerator.java

protected void processKey(SelectionKey key) {
    SessionSpi session = (SessionSpi) key.attachment();

    if (key.isAcceptable())
        session.onEvent(Constants.EV_ACCEPTABLE, null);
    if (key.isConnectable())
        session.onEvent(Constants.EV_CONNECTABLE, null);
    if (key.isValid() && key.isReadable())
        session.onEvent(Constants.EV_READABLE, null);
    if (key.isValid() && key.isWritable())
        session.onEvent(Constants.EV_WRITABLE, null);
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.IncomingConnectionThread.java

private void doRead(SelectionKey key) {

    final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
    try {/*from  w w  w.ja va 2s .  co m*/
        incomingConnection.read();
    } catch (EOFException eof) {
        if (incomingConnection.isCloseUnexpected()) {
            final SocketChannel socketChannel = (SocketChannel) key.channel();
            LOG.error("Connection from " + socketChannel.socket().getRemoteSocketAddress()
                    + " was closed unexpectedly");
            incomingConnection.reportTransmissionProblem(key, eof);
        } else {
            incomingConnection.closeConnection(key);
        }
    } catch (IOException ioe) {
        incomingConnection.reportTransmissionProblem(key, ioe);
    } catch (InterruptedException e) {
        // Nothing to do here
    } catch (NoBufferAvailableException e) {
        // There are no buffers available, unsubscribe from read event
        final SocketChannel socketChannel = (SocketChannel) key.channel();
        try {
            final SelectionKey newKey = socketChannel.register(this.selector, 0);
            newKey.attach(incomingConnection);
        } catch (ClosedChannelException e1) {
            incomingConnection.reportTransmissionProblem(key, e1);
        }

        final BufferAvailabilityListener bal = new IncomingConnectionBufferAvailListener(
                this.pendingReadEventSubscribeRequests, key);
        if (!e.getBufferProvider().registerBufferAvailabilityListener(bal)) {
            // In the meantime, a buffer has become available again, subscribe to read event again

            try {
                final SelectionKey newKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
                newKey.attach(incomingConnection);
            } catch (ClosedChannelException e1) {
                incomingConnection.reportTransmissionProblem(key, e1);
            }
        }
    }
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

private void doWrite(SelectionKey key) {

    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();

    try {/*from  w  w  w.  j  ava 2 s.com*/

        if (!outgoingConnection.write()) {
            // Try to close the connection
            outgoingConnection.requestClose();
        }

    } catch (IOException ioe) {
        outgoingConnection.reportTransmissionProblem(ioe);
    }
}

From source file:net.sf.cindy.impl.SimpleEventGenerator.java

protected void finishedSelect(Selector selector) {
    for (Iterator iter = selector.keys().iterator(); iter.hasNext();) {
        SelectionKey key = (SelectionKey) iter.next();
        Session session = (Session) key.attachment();
        session.close();//from   ww w .  j  a v a 2 s  .c  o  m
    }
    try {
        selector.close();
    } catch (IOException e) {
    }
    selector = null;
    lastSelectTime = null;
    register.clear();
    close = false;
    thread = null;
}

From source file:eu.stratosphere.nephele.taskmanager.bytebuffered.OutgoingConnectionThread.java

private void doConnect(SelectionKey key) {

    final OutgoingConnection outgoingConnection = (OutgoingConnection) key.attachment();
    final SocketChannel socketChannel = (SocketChannel) key.channel();
    try {//from  w  w w .j a v a 2 s .c o  m
        while (!socketChannel.finishConnect()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e1) {
                LOG.error(e1);
            }
        }

        final SelectionKey channelKey = socketChannel.register(selector,
                SelectionKey.OP_WRITE | SelectionKey.OP_READ);
        outgoingConnection.setSelectionKey(channelKey);
        channelKey.attach(outgoingConnection);

    } catch (IOException ioe) {
        outgoingConnection.reportConnectionProblem(ioe);
    }
}

From source file:gridool.communication.transport.tcp.GridNioServer.java

private static void handleRead(final SocketChannel channel, final SelectionKey key,
        final ByteBuffer sharedReadBuf, final GridTransportListener notifier, final ExecutorService exec) {
    sharedReadBuf.clear();// ww  w  . j a v  a  2s  . c  o m
    final SocketAddress remoteAddr = channel.socket().getRemoteSocketAddress();
    final int bytesRead;
    try {
        bytesRead = channel.read(sharedReadBuf);
    } catch (IOException e) {
        LOG.warn("Failed to read data from client: " + remoteAddr, e);
        NIOUtils.close(key);
        return;
    }
    if (LOG.isDebugEnabled()) {
        LOG.debug("Read " + bytesRead + " bytes from a client socket: " + remoteAddr);
    }
    if (bytesRead == -1) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("Remote client closed connection: " + remoteAddr);
        }
        NIOUtils.close(key);
        return;
    } else if (bytesRead == 0) {
        return;
    }

    final GridMessageBuffer msgBuf = (GridMessageBuffer) key.attachment();
    sharedReadBuf.flip();
    while (sharedReadBuf.remaining() > 0) {
        msgBuf.read(sharedReadBuf);
        if (msgBuf.isFilled()) {
            exec.execute(new Runnable() {
                public void run() {
                    final GridCommunicationMessage msg = msgBuf.toMessage();
                    msgBuf.reset();
                    if (LOG.isDebugEnabled()) {
                        LOG.debug("Recieved a GridCommunicationMessage [" + msg.getMessageId() + "]");
                    }
                    notifier.notifyListener(msg);
                }
            });
            break;
        }
    }
}

From source file:net.sf.cindy.impl.SimpleEventGenerator.java

private void checkSessionTimeout() {
    if (lastSelectTime == null) {
        lastSelectTime = new ElapsedTime();
        return;/*from  www .ja  v  a  2 s. c o m*/
    }

    Set selectedKeys = selector.selectedKeys();
    for (Iterator iter = selectedKeys.iterator(); iter.hasNext();) {
        SelectionKey key = (SelectionKey) iter.next();
        SessionSpi session = (SessionSpi) key.attachment();
        session.onEvent(Constants.EV_EVENT_HAPPEN, null);
    }

    //imporve performance, do not check session timeout frequently
    if (lastSelectTime.getElapsedTime() >= Constants.CHECK_SESSION_TIMEOUT_INTERVAL) {
        Integer interval = new Integer((int) lastSelectTime.reset());
        for (Iterator iter = selector.keys().iterator(); iter.hasNext();) {
            SelectionKey key = (SelectionKey) iter.next();
            if (!selectedKeys.contains(key)) { //no event happen, check timeout
                SessionSpi session = (SessionSpi) key.attachment();
                session.onEvent(Constants.EV_CHECK_TIMEOUT, interval);
            }
        }
    }
}