Example usage for java.nio.channels SelectionKey OP_CONNECT

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

Introduction

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

Prototype

int OP_CONNECT

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

Click Source Link

Document

Operation-set bit for socket-connect operations.

Usage

From source file:com.facebook.infrastructure.net.TcpConnection.java

private void setupChannel() throws IOException {
    socketChannel_ = SocketChannel.open();
    socketChannel_.configureBlocking(false);
    logger_.info("Opening socketchannel to " + remoteEp_.getInetAddress() + "(" + socketChannel_ + ")");
    if (!socketChannel_.connect(remoteEp_.getInetAddress())) {
        key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_CONNECT);
    } else {/*from ww w  .  j ava  2 s . c om*/
        key_ = SelectorManager.getSelectorManager().register(socketChannel_, this, SelectionKey.OP_READ);
        connected_.set(true);
    }
}

From source file:co.elastic.tealess.SSLChecker.java

private void checkConnect(SSLReport sslReport, SocketChannel socket, long timeout) {
    final InetSocketAddress address = sslReport.getAddress();
    try {//from w ww.j  av  a2s  . c o  m
        logger.trace("Connecting to {}", address);
        Selector selector = Selector.open();
        SelectionKey sk = socket.register(selector, SelectionKey.OP_CONNECT);
        socket.connect(address);
        selector.select(timeout);
        if (!sk.isConnectable()) {
            sslReport.setFailed(new SocketTimeoutException());
            return;
        }
        if (socket.isConnectionPending()) {
            socket.finishConnect();
        }
    } catch (ConnectException e) {
        logger.debug("Connection failed to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    } catch (IOException e) {
        logger.error("Failed connecting to {}: {}", address, e);
        sslReport.setFailed(e);
        return;
    }

    logger.debug("Connection successful to {}", address);
}

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

/**
 * ???//www. j ava 2  s  . c  o m
 * 
 * @param proxy
 *       IProxy
 * @throws ClosedChannelException
 *       
 */
public void register(IProxy proxy) throws ClosedChannelException {
    SelectableChannel channel = proxy.channel();
    if (channel instanceof SocketChannel)
        channel.register(selector, SelectionKey.OP_CONNECT, proxy.getNIOHandler());
    else if (channel instanceof DatagramChannel)
        channel.register(selector, SelectionKey.OP_READ, proxy.getNIOHandler());
    if (!proxies.contains(proxy))
        proxies.add(proxy);
}

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

private static String describeInterestOps(int interestOps) {
    final TreeSet<String> result = new TreeSet<String>();
    if ((interestOps & SelectionKey.OP_ACCEPT) != 0)
        result.add("ACCEPT");
    if ((interestOps & SelectionKey.OP_CONNECT) != 0)
        result.add("CONNECT");
    if ((interestOps & SelectionKey.OP_READ) != 0)
        result.add("READ");
    if ((interestOps & SelectionKey.OP_WRITE) != 0)
        result.add("WRITE");
    return StringUtils.join(result, "|");
}

From source file:net.socket.nio.TimeClientHandle.java

private void doConnect() throws IOException {
    // ?????/*from ww w .j av a  2 s.  c o m*/
    if (socketChannel.connect(new InetSocketAddress(host, port))) {
        socketChannel.register(selector, SelectionKey.OP_READ);
        doWrite(socketChannel);
    } else {
        socketChannel.register(selector, SelectionKey.OP_CONNECT);
    }
}

From source file:ee.ria.xroad.proxy.clientproxy.FastestSocketSelector.java

private SocketInfo initConnections(Selector selector) throws IOException {
    log.trace("initConnections()");

    for (URI target : addresses) {
        SocketChannel channel = SocketChannel.open();
        channel.setOption(StandardSocketOptions.TCP_NODELAY, true);
        channel.configureBlocking(false);
        try {/*from   w w  w.  j  a  v a2  s . c  o m*/
            channel.register(selector, SelectionKey.OP_CONNECT, target);

            if (channel.connect(new InetSocketAddress(target.getHost(), target.getPort()))) { // connected immediately
                channel.configureBlocking(true);
                return new SocketInfo(target, channel.socket());
            }
        } catch (Exception e) {
            closeQuietly(channel);
            log.trace("Error connecting to '{}': {}", target, e);
        }
    }

    return null;
}

From source file:idgs.client.TcpClient.java

/**
 * /*from  ww  w.  ja  v a 2 s  .  c  om*/
 * @param timeout
 * @param retryTimes
 * @throws IOException
 */
public boolean connect(final boolean enableTimeoutCheck, final int timeout, final int retryTimes) {
    if (enableTimeoutCheck) {
        if (retryTimes <= 0) { // up to re-try times
            return isConnected();
        }
        Timer timer = new Timer(); // after timeout seconds, run timer task, if not connected, re-try again
        timer.schedule(new TimerTask() {
            public void run() {
                if (!isConnected()) {
                    int newRetryTimes = retryTimes - 1;
                    connect(enableTimeoutCheck, timeout, newRetryTimes);
                }
            }
        }, timeout);
    }
    try {
        SocketChannel channel = SocketChannel.open();
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_CONNECT);
        channel.connect(servAddr);
        select();
    } catch (IOException e) {
        log.warn("try to connecte to server[" + servAddr.toString() + "] error, " + e.getMessage());
    }
    return isConnected();
}

From source file:com.buaa.cfs.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 *
 * @param channel  - this should be a {@link SelectableChannel}
 * @param endpoint//from  w  w w. j  a v  a  2  s  . com
 *
 * @throws IOException
 * @see SocketChannel#connect(SocketAddress)
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (Time.now() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - Time.now())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}

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

@Override
protected void handle(SelectionKey key) {
    System.out.println("ReadWriteThread.handle() " + describeInterestOps(key.interestOps()) + ", ready: "
            + describeInterestOps(key.readyOps()));
    switch (key.readyOps()) {
    case SelectionKey.OP_CONNECT:
        finishConnection(key);// w w  w .j  av a  2 s.co  m
        break;
    case SelectionKey.OP_READ:
        readPacket(key);
        break;
    case SelectionKey.OP_WRITE:
        writePacket(key);
        break;
    case SelectionKey.OP_READ | SelectionKey.OP_WRITE:
        writePacket(key);
        // key might have been invalidated on writePacket
        if (key.isValid())
            readPacket(key);
        break;
    default:
        System.err.println("Unknown readyOps: " + key.readyOps() + " for " + key.attachment());
        break;
    }
}

From source file:eu.stratosphere.nephele.net.SocketIOWithTimeout.java

/**
 * The contract is similar to {@link SocketChannel#connect(SocketAddress)} with a timeout.
 * //from w w  w. j a v a  2 s. co  m
 * @see SocketChannel#connect(SocketAddress)
 * @param channel
 *        - this should be a {@link SelectableChannel}
 * @param endpoint
 * @throws IOException
 */
static void connect(SocketChannel channel, SocketAddress endpoint, int timeout) throws IOException {

    boolean blockingOn = channel.isBlocking();
    if (blockingOn) {
        channel.configureBlocking(false);
    }

    try {
        if (channel.connect(endpoint)) {
            return;
        }

        long timeoutLeft = timeout;
        long endTime = (timeout > 0) ? (System.currentTimeMillis() + timeout) : 0;

        while (true) {
            // we might have to call finishConnect() more than once
            // for some channels (with user level protocols)

            int ret = selector.select((SelectableChannel) channel, SelectionKey.OP_CONNECT, timeoutLeft);

            if (ret > 0 && channel.finishConnect()) {
                return;
            }

            if (ret == 0 || (timeout > 0 && (timeoutLeft = (endTime - System.currentTimeMillis())) <= 0)) {
                throw new SocketTimeoutException(
                        timeoutExceptionString(channel, timeout, SelectionKey.OP_CONNECT));
            }
        }
    } catch (IOException e) {
        // javadoc for SocketChannel.connect() says channel should be closed.
        try {
            channel.close();
        } catch (IOException ignored) {
        }
        throw e;
    } finally {
        if (blockingOn && channel.isOpen()) {
            channel.configureBlocking(true);
        }
    }
}