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, Object att) throws ClosedChannelException 

Source Link

Document

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

Usage

From source file:org.apache.htrace.impl.PackedBufferManager.java

private SelectionKey doConnect() throws IOException {
    SocketChannel sock = SocketChannel.open();
    SelectionKey sockKey = null;/*from   w ww. ja  v a 2 s.  c  o m*/
    boolean success = false;
    try {
        if (sock.isBlocking()) {
            sock.configureBlocking(false);
        }
        InetSocketAddress resolvedEndpoint = new InetSocketAddress(conf.endpoint.getHostString(),
                conf.endpoint.getPort());
        resolvedEndpoint.getHostName(); // trigger DNS resolution
        sock.connect(resolvedEndpoint);
        sockKey = sock.register(selector, SelectionKey.OP_CONNECT, sock);
        long startMs = TimeUtil.nowMs();
        long remainingMs = conf.connectTimeoutMs;
        while (true) {
            selector.select(remainingMs);
            for (SelectionKey key : selector.keys()) {
                if (key.isConnectable()) {
                    SocketChannel s = (SocketChannel) key.attachment();
                    s.finishConnect();
                    if (LOG.isTraceEnabled()) {
                        LOG.trace("Successfully connected to " + conf.endpointStr + ".");
                    }
                    success = true;
                    return sockKey;
                }
            }
            remainingMs = updateRemainingMs(startMs, conf.connectTimeoutMs);
            if (remainingMs == 0) {
                throw new IOException("Attempt to connect to " + conf.endpointStr + " timed out after "
                        + TimeUtil.deltaMs(startMs, TimeUtil.nowMs()) + " ms.");
            }
        }
    } finally {
        if (!success) {
            if (sockKey != null) {
                sockKey.cancel();
            }
            sock.close();
        }
    }
}

From source file:voldemort.server.niosocket.NioSelectorManager.java

@Override
protected void processEvents() {
    try {/*from   w  ww  . j  ava 2s .  c  o m*/
        SocketChannel socketChannel = null;

        while ((socketChannel = socketChannelQueue.poll()) != null) {
            if (isClosed.get()) {
                if (logger.isInfoEnabled())
                    logger.debug("Closed, exiting for " + endpoint);

                break;
            }

            try {
                if (logger.isDebugEnabled())
                    logger.debug("Registering connection from " + socketChannel.socket().getPort());

                socketChannel.socket().setTcpNoDelay(true);
                socketChannel.socket().setReuseAddress(true);
                socketChannel.socket().setSendBufferSize(socketBufferSize);

                if (socketChannel.socket().getReceiveBufferSize() != this.socketBufferSize)
                    if (logger.isDebugEnabled())
                        logger.debug("Requested socket receive buffer size was " + this.socketBufferSize
                                + " bytes but actual size is " + socketChannel.socket().getReceiveBufferSize()
                                + " bytes.");

                if (socketChannel.socket().getSendBufferSize() != this.socketBufferSize)
                    if (logger.isDebugEnabled())
                        logger.debug("Requested socket send buffer size was " + this.socketBufferSize
                                + " bytes but actual size is " + socketChannel.socket().getSendBufferSize()
                                + " bytes.");

                socketChannel.configureBlocking(false);
                AsyncRequestHandler attachment = new AsyncRequestHandler(selector, socketChannel,
                        requestHandlerFactory, socketBufferSize, numActiveConnections);

                if (!isClosed.get()) {
                    socketChannel.register(selector, SelectionKey.OP_READ, attachment);
                    numActiveConnections.increment();
                }
            } catch (ClosedSelectorException e) {
                if (logger.isDebugEnabled())
                    logger.debug("Selector is closed, exiting");

                close();

                break;
            } catch (Exception e) {
                if (logger.isEnabledFor(Level.ERROR))
                    logger.error(e.getMessage(), e);
            }
        }
    } catch (Exception e) {
        if (logger.isEnabledFor(Level.ERROR))
            logger.error(e.getMessage(), e);
    }
}