Example usage for java.nio.channels SocketChannel open

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

Introduction

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

Prototype

public static SocketChannel open() throws IOException 

Source Link

Document

Opens a socket channel.

Usage

From source file:gda.device.scannable.keyence.Keyence.java

/**
 * Set up initial connections to socket and wrap the stream in buffered reader and writer.
 * @throws DeviceException /*www . ja  v a 2  s  .c o m*/
 */
public void connect() throws DeviceException {
    try {
        synchronized (socketAccessLock) {
            if (!isConnected()) {
                InetSocketAddress inetAddr = new InetSocketAddress(host, commandPort);
                socketChannel = SocketChannel.open();
                socketChannel.connect(inetAddr);

                socketChannel.socket().setSoTimeout(socketTimeOut);
                socketChannel.configureBlocking(true);
                socketChannel.finishConnect();

                cleanPipe();
                doStartupScript();

                connected = true;
            }
        }
    } catch (UnknownHostException ex) {
        // this could be fatal as reconnect attempts are futile.
        logger.error(getName() + ": connect: " + ex.getMessage());
    } catch (ConnectException ex) {
        logger.debug(getName() + ": connect: " + ex.getMessage());
    } catch (IOException ix) {
        logger.error(getName() + ": connect: " + ix.getMessage());
    }
}

From source file:org.cloudata.core.commitlog.pipe.InitState.java

private void prepareNextConnection(Pipe.Context ctx, String nextAddress) throws IOException {
    ctx.nextChannel = SocketChannel.open();
    ctx.nextChannel.socket().setTcpNoDelay(true);

    ctx.nextChannel.configureBlocking(false);
    ctx.nextChannel.socket().setSoTimeout(CONNECTION_TIMEOUT);

    ctx.nextChannel.connect(new InetSocketAddress(getIP(nextAddress), getPort(nextAddress)));

    connectToNext(ctx);//from   w w w. j av a2 s.com
}

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 {/*w w w. j a  va 2  s  .  c om*/
            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:hornet.framework.clamav.pool.PooledSocketFactory.java

@Override
public SocketChannel create() {

    try {/*from w  ww  .  j  av a 2  s.  c om*/
        return SocketChannel.open();
    } catch (final IOException e) {
        LOGGER.error("Erreur lors de l'ouverture de la socket", e);
        return null;
    }
}

From source file:net.fenyo.mail4hotspot.service.HttpProxy.java

public int connect() throws IOException {
    last_use = System.currentTimeMillis();

    // log.debug("connect(): new Socket()");
    // final InetAddress address = InetAddress.getByAddress("xyz", new byte [] { (byte) 192, (byte) 168, (byte) 0, (byte) 5 /* 19 */ } );
    final InetAddress address = InetAddress.getByName(remote_host);
    final SocketAddress s_address = new InetSocketAddress(address, remote_port);
    socket_channel = SocketChannel.open();
    socket_channel.configureBlocking(true);
    socket_channel.connect(s_address);/*from w  ww .  j  a v  a 2  s  .  c  om*/
    socket_channel.configureBlocking(false);
    // log.debug("local port: " + ((InetSocketAddress) socket_channel.getLocalAddress()).getPort());

    local_port = ((InetSocketAddress) socket_channel.getLocalAddress()).getPort();

    return local_port;
}

From source file:idgs.client.TcpClient.java

/**
 * //from   w  w w .j a  va  2s  .c  o  m
 * @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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(timeOut = 15000)
public void testDirectConnectionToEchoServer() throws IOException {
    SocketChannel client = SocketChannel.open();
    try {//w w  w  .ja  v a  2s  .  c o  m
        client.connect(new InetSocketAddress("localhost", doubleEchoServer.getServerSocketPort()));
        writeToSocket(client, "Knock\n".getBytes());
        String response = readFromSocket(client);
        client.close();
        assertEquals(response, "Knock Knock\n");
    } finally {
        client.close();
    }
}

From source file:org.apache.gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(enabled = false, timeOut = 15000)
public void testDirectConnectionToEchoServer() throws IOException {
    SocketChannel client = SocketChannel.open();
    try {/*from ww w .j  av a2s.  com*/
        client.connect(new InetSocketAddress("localhost", doubleEchoServer.getServerSocketPort()));
        writeToSocket(client, "Knock\n".getBytes());
        String response = readFromSocket(client);
        client.close();
        assertEquals(response, "Knock Knock\n");
    } finally {
        client.close();
    }
}

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

private SelectionKey doConnect() throws IOException {
    SocketChannel sock = SocketChannel.open();
    SelectionKey sockKey = null;//from w w w.  j ava  2s . 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:gobblin.tunnel.TestTunnelWithArbitraryTCPTraffic.java

@Test(timeOut = 15000)
public void testTunnelToEchoServer() throws IOException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {/*w w  w . j a  v a 2 s  . c  om*/
        int tunnelPort = tunnel.getPort();
        SocketChannel client = SocketChannel.open();

        client.connect(new InetSocketAddress("localhost", tunnelPort));
        client.write(ByteBuffer.wrap("Knock\n".getBytes()));
        String response = readFromSocket(client);
        client.close();

        assertEquals(response, "Knock Knock\n");
        assertEquals(proxyServer.getNumConnects(), 1);
    } finally {
        proxyServer.stopServer();
        tunnel.close();
        assertFalse(tunnel.isTunnelThreadAlive());
    }
}