Example usage for java.nio.channels SocketChannel connect

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

Introduction

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

Prototype

public abstract boolean connect(SocketAddress remote) throws IOException;

Source Link

Document

Connects this channel's socket.

Usage

From source file:edu.hawaii.soest.kilonalu.tchain.TChainSource.java

/**
* A method used to the TCP socket of the remote source host for communication
* @param host       the name or IP address of the host to connect to for the
*                   socket connection (reading)
* @param portNumber the number of the TCP port to connect to (i.e. 2604)
*///w ww  .j a v  a 2s .com
protected SocketChannel getSocketConnection() {

    String host = getHostName();
    int portNumber = new Integer(getHostPort()).intValue();
    SocketChannel dataSocket = null;

    try {

        // create the socket channel connection to the data source via the 
        // converter serial2IP converter      
        dataSocket = SocketChannel.open();
        Socket tcpSocket = dataSocket.socket();
        tcpSocket.setTcpNoDelay(true);
        tcpSocket.setReceiveBufferSize(40);
        dataSocket.connect(new InetSocketAddress(host, portNumber));

        // if the connection to the source fails, also disconnect from the RBNB
        // server and return null
        if (!dataSocket.isConnected()) {
            dataSocket.close();
            disconnect();
            dataSocket = null;
        }
    } catch (UnknownHostException ukhe) {
        System.err.println("Unable to look up host: " + host + "\n");
        disconnect();
        dataSocket = null;
    } catch (IOException nioe) {
        System.err.println("Couldn't get I/O connection to: " + host);
        disconnect();
        dataSocket = null;
    } catch (Exception e) {
        disconnect();
        dataSocket = null;
    }
    return dataSocket;

}

From source file:com.cloud.agent.resource.virtualnetwork.VirtualRoutingResource.java

public String connect(final String ipAddress, final int port) {
    for (int i = 0; i <= _retry; i++) {
        SocketChannel sch = null;
        try {/*  w  w  w .j a  v  a 2  s . c  om*/
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Trying to connect to " + ipAddress);
            }
            sch = SocketChannel.open();
            sch.configureBlocking(true);

            final InetSocketAddress addr = new InetSocketAddress(ipAddress, port);
            sch.connect(addr);
            return null;
        } catch (final IOException e) {
            if (s_logger.isDebugEnabled()) {
                s_logger.debug("Could not connect to " + ipAddress);
            }
        } finally {
            if (sch != null) {
                try {
                    sch.close();
                } catch (final IOException e) {
                }
            }
        }
        try {
            Thread.sleep(_sleep);
        } catch (final InterruptedException e) {
        }
    }

    s_logger.debug("Unable to logon to " + ipAddress);

    return "Unable to connect";
}

From source file:HttpDownloadManager.java

public void run() {
    log.info("HttpDownloadManager thread starting.");

    // The download thread runs until release() is called
    while (!released) {
        // The thread blocks here waiting for something to happen
        try {/*  ww w .ja va2  s  .c o  m*/
            selector.select();
        } catch (IOException e) {
            // This should never happen.
            log.log(Level.SEVERE, "Error in select()", e);
            return;
        }

        // If release() was called, the thread should exit.
        if (released)
            break;

        // If any new Download objects are pending, deal with them first
        if (!pendingDownloads.isEmpty()) {
            // Although pendingDownloads is a synchronized list, we still
            // need to use a synchronized block to iterate through its
            // elements to prevent a concurrent call to download().
            synchronized (pendingDownloads) {
                Iterator iter = pendingDownloads.iterator();
                while (iter.hasNext()) {
                    // Get the pending download object from the list
                    DownloadImpl download = (DownloadImpl) iter.next();
                    iter.remove(); // And remove it.

                    // Now begin an asynchronous connection to the
                    // specified host and port. We don't block while
                    // waiting to connect.
                    SelectionKey key = null;
                    SocketChannel channel = null;
                    try {
                        // Open an unconnected channel
                        channel = SocketChannel.open();
                        // Put it in non-blocking mode
                        channel.configureBlocking(false);
                        // Register it with the selector, specifying that
                        // we want to know when it is ready to connect
                        // and when it is ready to read.
                        key = channel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_CONNECT,
                                download);
                        // Create the web server address
                        SocketAddress address = new InetSocketAddress(download.host, download.port);
                        // Ask the channel to start connecting
                        // Note that we don't send the HTTP request yet.
                        // We'll do that when the connection completes.
                        channel.connect(address);
                    } catch (Exception e) {
                        handleError(download, channel, key, e);
                    }
                }
            }
        }

        // Now get the set of keys that are ready for connecting or reading
        Set keys = selector.selectedKeys();
        if (keys == null)
            continue; // bug workaround; should not be needed
        // Loop through the keys in the set
        for (Iterator i = keys.iterator(); i.hasNext();) {
            SelectionKey key = (SelectionKey) i.next();
            i.remove(); // Remove the key from the set before handling

            // Get the Download object we attached to the key
            DownloadImpl download = (DownloadImpl) key.attachment();
            // Get the channel associated with the key.
            SocketChannel channel = (SocketChannel) key.channel();

            try {
                if (key.isConnectable()) {
                    // If the channel is ready to connect, complete the
                    // connection and then send the HTTP GET request to it.
                    if (channel.finishConnect()) {
                        download.status = Status.CONNECTED;
                        // This is the HTTP request we wend
                        String request = "GET " + download.path + " HTTP/1.1\r\n" + "Host: " + download.host
                                + "\r\n" + "Connection: close\r\n" + "\r\n";
                        // Wrap in a CharBuffer and encode to a ByteBuffer
                        ByteBuffer requestBytes = LATIN1.encode(CharBuffer.wrap(request));
                        // Send the request to the server. If the bytes
                        // aren't all written in one call, we busy loop!
                        while (requestBytes.hasRemaining())
                            channel.write(requestBytes);

                        log.info("Sent HTTP request: " + download.host + ":" + download.port + ": " + request);
                    }
                }
                if (key.isReadable()) {
                    // If the key indicates that there is data to be read,
                    // then read it and store it in the Download object.
                    int numbytes = channel.read(buffer);

                    // If we read some bytes, store them, otherwise
                    // the download is complete and we need to note this
                    if (numbytes != -1) {
                        buffer.flip(); // Prepare to drain the buffer
                        download.addData(buffer); // Store the data
                        buffer.clear(); // Prepare for another read
                        log.info("Read " + numbytes + " bytes from " + download.host + ":" + download.port);
                    } else {
                        // If there are no more bytes to read
                        key.cancel(); // We're done with the key
                        channel.close(); // And with the channel.
                        download.status = Status.DONE;
                        if (download.listener != null) // notify listener
                            download.listener.done(download);
                        log.info("Download complete from " + download.host + ":" + download.port);
                    }
                }
            } catch (Exception e) {
                handleError(download, channel, key, e);
            }
        }
    }
    log.info("HttpDownloadManager thread exiting.");
}

From source file:com.byteatebit.nbserver.simple.client.SimpleNbClient.java

public void tcpConnect(String remoteHost, int remotePort, IClientSocketChannelHandler socketChannelHandler,
        long timeout) throws IOException {
    if (!initialized.get())
        throw new IllegalStateException("SimpleNbClient must first be initialized via init()");
    SocketChannel socketChannel = SocketChannel.open();
    socketChannel.configureBlocking(false);
    InetSocketAddress address = new InetSocketAddress(remoteHost, remotePort);
    INbContext nbContext = new NbContext(simpleNbService.getSelectorRegistrarBalancer().getSelectorRegistrar(),
            simpleNbService.getScheduler());
    IOTask connectTask = (selectionKey) -> {
        boolean connectionFinished = false;
        try {//  w  w w .  ja  va  2  s.  c  o m
            connectionFinished = socketChannel.finishConnect();
        } catch (IOException e) {
            LOG.error("Could not complete socket connection.", e);
        }
        if (!connectionFinished) {
            LOG.error("Could not complete socket connection.  Closing socket channel");
            selectionKey.cancel();
            IOUtils.closeQuietly(socketChannel);
            socketChannelHandler.connectFailed(remoteHost, remotePort);
            return;
        }
        selectionKey.interestOps(selectionKey.interestOps() & ~SelectionKey.OP_CONNECT);
        socketChannelHandler.accept(nbContext, socketChannel);
    };
    IOTimeoutTask timeoutTask = (selectionKey, ops) -> {
        LOG.error("Connect attempt timed out after " + timeout + " ms");
        selectionKey.cancel();
        IOUtils.closeQuietly(socketChannel);
        socketChannelHandler.connectFailed(remoteHost, remotePort);
    };
    nbContext.register(socketChannel, SelectionKey.OP_CONNECT, connectTask, timeoutTask, timeout);
    socketChannel.connect(address);
}

From source file:edu.hawaii.soest.kilonalu.ctd.CTDSource.java

/**
* A method used to the TCP socket of the remote source host for communication
* @param host       the name or IP address of the host to connect to for the
*                   socket connection (reading)
* @param portNumber the number of the TCP port to connect to (i.e. 2604)
*//*www .  j  ava2 s. co m*/
protected SocketChannel getSocketConnection() {

    String host = getHostName();
    int portNumber = new Integer(getHostPort()).intValue();
    SocketChannel dataSocket = null;

    try {

        // create the socket channel connection to the data source via the 
        // converter serial2IP converter      
        dataSocket = SocketChannel.open();
        dataSocket.connect(new InetSocketAddress(host, portNumber));

        // if the connection to the source fails, also disconnect from the RBNB
        // server and return null
        if (!dataSocket.isConnected()) {
            dataSocket.close();
            disconnect();
            dataSocket = null;
        }
    } catch (UnknownHostException ukhe) {

        logger.info("Unable to look up host: " + host + "\n");
        disconnect();
        dataSocket = null;
    } catch (IOException nioe) {
        logger.info("Couldn't get I/O connection to: " + host);
        disconnect();
        dataSocket = null;
    } catch (Exception e) {
        disconnect();
        dataSocket = null;
    }
    return dataSocket;

}

From source file:net.timewalker.ffmq4.transport.tcp.nio.NIOTcpPacketTransport.java

/**
  * Connect the transport to its remote endpoint
  *//*from w w  w  . j  ava 2s.  c o  m*/
private SocketChannel connect(URI transportURI) throws PacketTransportException {
    String host = transportURI.getHost();
    int port = transportURI.getPort();

    try {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.configureBlocking(false);
        SocketUtils.setupSocket(socketChannel.socket(), socketSendBufferSize, socketRecvBufferSize);

        log.debug("#" + id + " opening a TCP connection to " + host + ":" + port);
        socketChannel.connect(new InetSocketAddress(host, port));

        return socketChannel;
    } catch (Exception e) {
        log.error("#" + id + " could not connect to " + host + ":" + port, e);
        throw new PacketTransportException("Could not connect to " + host + ":" + port + " : " + e.toString());
    }
}

From source file:net.ymate.platform.serv.nio.support.NioEventGroup.java

@SuppressWarnings("unchecked")
protected INioSession __doSessionCreate(IClientCfg cfg) throws IOException {
    SocketChannel _channel = SocketChannel.open();
    _channel.configureBlocking(false);/* w w  w.j  a va 2  s . c  o m*/
    _channel.socket().setReuseAddress(true);
    _channel.connect(new InetSocketAddress(cfg.getRemoteHost(), cfg.getPort()));
    __channel = _channel;
    return new NioSession(this, _channel);
}

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 .  ja va  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 testTunnelToEchoServer() throws IOException {
    MockServer proxyServer = startConnectProxyServer();
    Tunnel tunnel = Tunnel.build("localhost", doubleEchoServer.getServerSocketPort(), "localhost",
            proxyServer.getServerSocketPort());

    try {//from  w w w.ja  va 2 s . com
        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());
    }
}

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

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

    try {// w  ww.j a  v a  2 s .  c o m
        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());
    }
}