Example usage for java.nio.channels SocketChannel register

List of usage examples for java.nio.channels SocketChannel register

Introduction

In this page you can find the example usage for java.nio.channels SocketChannel register.

Prototype

public final SelectionKey register(Selector sel, int ops) throws ClosedChannelException 

Source Link

Document

Registers this channel with the given selector, returning a selection key.

Usage

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

public void unsubscribeFromWriteEvent(SelectionKey selectionKey) throws IOException {

    final SocketChannel socketChannel = (SocketChannel) selectionKey.channel();
    final OutgoingConnection outgoingConnection = (OutgoingConnection) selectionKey.attachment();

    final SelectionKey newSelectionKey = socketChannel.register(this.selector, SelectionKey.OP_READ);
    newSelectionKey.attach(outgoingConnection);
    outgoingConnection.setSelectionKey(newSelectionKey);

    synchronized (this.connectionsToClose) {
        this.connectionsToClose.put(outgoingConnection, Long.valueOf(System.currentTimeMillis()));
    }/*from w  w w  . j a v a2 s . co  m*/
}

From source file:org.reunionemu.jreunion.server.Network.java

private void processAccept(SocketChannel socketChannel) throws IOException {

    socketChannel.configureBlocking(false);

    fireEvent(NetworkAcceptEvent.class, socketChannel);

    // Register it with the selector, for reading
    selector.wakeup();//ww  w  .  j av a2 s . c  o  m
    socketChannel.register(selector, SelectionKey.OP_READ);

}

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

@Override
public void run() {

    while (!isInterrupted()) {

        synchronized (this.pendingConnectionRequests) {

            if (!this.pendingConnectionRequests.isEmpty()) {

                final OutgoingConnection outgoingConnection = this.pendingConnectionRequests.poll();
                try {
                    final SocketChannel socketChannel = SocketChannel.open();
                    socketChannel.configureBlocking(false);
                    final SelectionKey key = socketChannel.register(this.selector, SelectionKey.OP_CONNECT);
                    socketChannel.connect(outgoingConnection.getConnectionAddress());
                    key.attach(outgoingConnection);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportConnectionProblem(ioe);
                        }//from   ww  w .  j  ava2 s  . c om
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.pendingWriteEventSubscribeRequests) {

            if (!this.pendingWriteEventSubscribeRequests.isEmpty()) {
                final SelectionKey oldSelectionKey = this.pendingWriteEventSubscribeRequests.poll();
                final OutgoingConnection outgoingConnection = (OutgoingConnection) oldSelectionKey.attachment();
                final SocketChannel socketChannel = (SocketChannel) oldSelectionKey.channel();

                try {
                    final SelectionKey newSelectionKey = socketChannel.register(this.selector,
                            SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                    newSelectionKey.attach(outgoingConnection);
                    outgoingConnection.setSelectionKey(newSelectionKey);
                } catch (final IOException ioe) {
                    // IOException is reported by separate thread to avoid deadlocks
                    final Runnable reporterThread = new Runnable() {

                        @Override
                        public void run() {
                            outgoingConnection.reportTransmissionProblem(ioe);
                        }
                    };
                    new Thread(reporterThread).start();
                }
            }
        }

        synchronized (this.connectionsToClose) {

            final Iterator<Map.Entry<OutgoingConnection, Long>> closeIt = this.connectionsToClose.entrySet()
                    .iterator();
            final long now = System.currentTimeMillis();
            while (closeIt.hasNext()) {

                final Map.Entry<OutgoingConnection, Long> entry = closeIt.next();
                if ((entry.getValue().longValue() + MIN_IDLE_TIME_BEFORE_CLOSE) < now) {
                    final OutgoingConnection outgoingConnection = entry.getKey();
                    closeIt.remove();
                    // Create new thread to close connection to avoid deadlocks
                    final Runnable closeThread = new Runnable() {

                        @Override
                        public void run() {
                            try {
                                outgoingConnection.closeConnection();
                            } catch (IOException ioe) {
                                outgoingConnection.reportTransmissionProblem(ioe);
                            }
                        }
                    };

                    new Thread(closeThread).start();
                }

            }
        }

        try {
            this.selector.select(10);
        } catch (IOException e) {
            LOG.error(e);
        }

        final Iterator<SelectionKey> iter = this.selector.selectedKeys().iterator();

        while (iter.hasNext()) {
            final SelectionKey key = iter.next();

            iter.remove();
            if (key.isValid()) {
                if (key.isConnectable()) {
                    doConnect(key);
                } else {
                    if (key.isReadable()) {
                        doRead(key);
                        // A read will always result in an exception, so the write key will not be valid anymore
                        continue;
                    }
                    if (key.isWritable()) {
                        doWrite(key);
                    }
                }
            } else {
                LOG.error("Received invalid key: " + key);
            }
        }
    }

    // Finally, try to close the selector
    try {
        this.selector.close();
    } catch (IOException ioe) {
        LOG.debug(StringUtils.stringifyException(ioe));
    }
}

From source file:org.reunionemu.jreunion.server.Network.java

public void notifySend(SocketChannel socketChannel) {
    try {/*from  w  w  w  . ja v a 2s .co  m*/
        // we synchronize this to make sure we register the key before the selector gets back to sleep again.
        if (socketChannel.isOpen() && selector.isOpen()) {
            selector.wakeup();
            socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);

        }

    } catch (ClosedChannelException e) {
        //Disconnect detected
    } catch (CancelledKeyException e) {

    } catch (Exception e) {

        LoggerFactory.getLogger(this.getClass()).error("Exception", e);

    }
}

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   www.  j  a  v  a 2s.c om*/
        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:com.tera.common.network.nio.MMOConnection.java

protected MMOConnection(PacketService packetService, SelectorThread selectorThread, SocketChannel socketChannel)
        throws ClosedChannelException {
    super(packetService);
    this.selectorThread = selectorThread;
    this.readWriteThread = getSelectorThread().getReadWriteThread();
    this.socket = socketChannel.socket();
    this.inetAddress = socket.getInetAddress();
    this.hostAddress = inetAddress.getHostAddress();
    this.selectionKey = socketChannel.register(getReadWriteThread().getSelector(), SelectionKey.OP_READ);
    this.selectionKey.attach(this);
    setChannelState(ChannelState.CONNECTED);
    connectionId = idFactory.nextId();//TODO deallocate after disconnect
}

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

private void doAccept(SelectionKey key) {

    SocketChannel clientSocket = null;

    try {/*from   ww w. ja va2  s .  c  om*/
        clientSocket = this.listeningSocket.accept();
        if (clientSocket == null) {
            LOG.error("Client socket is null");
            return;
        }
    } catch (IOException ioe) {
        LOG.error(ioe);
        return;
    }

    final IncomingConnection incomingConnection = new IncomingConnection(this.byteBufferedChannelManager,
            clientSocket);
    SelectionKey clientKey = null;
    try {
        clientSocket.configureBlocking(false);
        clientKey = clientSocket.register(this.selector, SelectionKey.OP_READ);
        clientKey.attach(incomingConnection);
    } catch (IOException ioe) {
        incomingConnection.reportTransmissionProblem(clientKey, ioe);
    }
}

From source file:oz.hadoop.yarn.api.net.ApplicationContainerServerImpl.java

/**
 * /*from  w ww  .ja v  a  2  s.c o  m*/
 */
@Override
void doAccept(SelectionKey selectionKey) throws IOException {
    ServerSocketChannel serverChannel = (ServerSocketChannel) selectionKey.channel();
    SocketChannel channel = serverChannel.accept();

    if (this.expectedClientContainersMonitor.getCount() == 0) {
        logger.warn("Refusing connection from " + channel.getRemoteAddress() + ", since "
                + this.expectedClientContainers + " ApplicationContainerClients "
                + "identified by 'expectedClientContainers' already connected.");
        this.closeChannel(channel);
    } else {
        channel.configureBlocking(false);
        SelectionKey clientSelectionKey = channel.register(this.selector, SelectionKey.OP_READ);
        if (logger.isInfoEnabled()) {
            logger.info("Accepted conection request from: " + channel.socket().getRemoteSocketAddress());
        }
        if (this.masterSelectionKey != null) {
            this.containerDelegates.put(clientSelectionKey,
                    new ContainerDelegateImpl(clientSelectionKey, this));
        } else {
            this.masterSelectionKey = clientSelectionKey;
            this.masterSelectionKey.attach(true);
        }
        this.expectedClientContainersMonitor.countDown();
    }
}

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

private void doRead(SelectionKey key) {

    final IncomingConnection incomingConnection = (IncomingConnection) key.attachment();
    try {/*ww  w  .  jav a2 s.  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:org.reunionemu.jreunion.server.Network.java

@Override
public void run() {
    logger.info("network thread starting");
    while (true) {
        try {//w w  w. j a v  a 2  s . c  o m
            // See if we've had any activity -- either an incoming connection,
            // or incoming data on an existing connection
            int num = selector.select();
            if (num == 0) {
                // we need synchronize here otherwise we might block again before we were able to change the selector
                synchronized (this) {
                    continue;
                }
            }

            // If we don't have any activity, loop around and wait again
            // Get the keys corresponding to the activity
            // that has been detected, and process them one by one

            Set<SelectionKey> keys = selector.selectedKeys();
            Iterator<SelectionKey> it = keys.iterator();
            while (it.hasNext()) {
                // Get a key representing one of bits of I/O activity
                SelectionKey key = it.next();
                if (!key.isValid())
                    continue;

                SelectableChannel selectableChannel = key.channel();
                // What kind of activity is it?
                if ((key.readyOps() & SelectionKey.OP_ACCEPT) == SelectionKey.OP_ACCEPT) {

                    // It's an incoming connection.
                    // Register this socket with the Selector
                    // so we can listen for input on it                  

                    SocketChannel clientSocketChannel = ((ServerSocketChannel) selectableChannel).accept();

                    processAccept(clientSocketChannel);

                } else {
                    SocketChannel socketChannel = (SocketChannel) selectableChannel;

                    if ((key.readyOps() & SelectionKey.OP_READ) == SelectionKey.OP_READ) {

                        // It's incoming data on a connection, so process it
                        boolean ok = processInput(socketChannel);

                        // If the connection is dead, then remove it
                        // from the selector and close it
                        if (!ok) {
                            LoggerFactory.getLogger(Network.class).info("Client Connection Lost");
                            key.cancel();
                            disconnect(socketChannel);
                        }

                    } else if ((key.readyOps() & SelectionKey.OP_WRITE) == SelectionKey.OP_WRITE) {

                        boolean ok = processOutput(socketChannel);
                        if (ok) {
                            socketChannel.register(selector, SelectionKey.OP_READ);
                        }
                    }
                }
            }
            // We remove the selected keys, because we've dealt with them.
            keys.clear();

        } catch (Exception e) {
            if (e instanceof ClosedSelectorException || e instanceof InterruptedException)
                return;
            LoggerFactory.getLogger(Network.class).error("Error in network", e);
        }
    }

}