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:com.mobicage.rpc.newxmpp.XMPPConfigurationFactory.java

public ConnectionConfiguration getSafeXmppConnectionConfiguration(final String xmppServiceName,
        final String email, final boolean hasFailed) throws XMPPConfigurationException {

    debuglog("Creating new XMPP connection");

    if (!mConnectivityManager.isConnected()) {
        debuglog("No network.");
        throw new XMPPConfigurationException("No network.");
    }/*  ww w  .  j a v  a 2s  .  c  o m*/

    final ConnectionConfiguration xmppConfig;
    if (hasFailed) {
        debuglog("Getting config from cloud because previous connection attempt failed.");
        xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email);
    } else {
        debuglog("Getting config from config provider.");
        ConnectionConfiguration tmpXmppConfig = getBasicXMPPConfigurationFromConfigProvider(xmppServiceName);
        if (tmpXmppConfig == null) {
            debuglog("Getting config from cloud because config provider is empty.");
            xmppConfig = getBasicXMPPConfigurationFromCloud(xmppServiceName, email);
        } else
            xmppConfig = tmpXmppConfig;
    }

    if (xmppConfig == null) {
        debuglog("No xmpp configuration found.");
        throw new XMPPConfigurationException("No xmpp configuration found.");
    }

    final HostAddress[] hostAddresses = xmppConfig.getHosts();
    if (hostAddresses.length == 0) {
        debuglog("Error: did not receive any XMPP DNS SRV record");
        throw new XMPPConfigurationException("Did not find any XMPP DNS SRV record");
    } else if (hostAddresses.length == 1 && xmppServiceName.equals(hostAddresses[0].getHost())
            && XMPP_DEFAULT_PORT == hostAddresses[0].getPort()) {
        buglog("Using fallback value for DNS SRV (but network is up): " + hostAddresses[0]);
    }

    debuglog("Found XMPP DNS SRV records:");
    for (int i = hostAddresses.length - 1; i >= 0; i--) {
        debuglog("- host = " + hostAddresses[i]);
    }

    final int preferredXMPPPort = hostAddresses[hostAddresses.length - 1].getPort();
    debuglog("Preferred XMPP port is " + preferredXMPPPort);

    // Do non-blocking TCP connect attempts
    Map<HostAddress, SocketChannel> allChannels = new HashMap<HostAddress, SocketChannel>();
    Map<HostAddress, SocketChannel> remainingChannels = new HashMap<HostAddress, SocketChannel>();
    for (int i = hostAddresses.length - 1; i >= 0; i--) {
        final HostAddress ha = hostAddresses[i];
        try {
            SocketChannel sChannel = SocketChannel.open();
            allChannels.put(ha, sChannel);
            sChannel.configureBlocking(false);
            sChannel.connect(new InetSocketAddress(ha.getHost(), ha.getPort()));
            remainingChannels.put(ha, sChannel);
        } catch (IOException e) {
            // Cannot connect to one socket ; let's not drop others
            debuglog("Ignoring socket due to connection error: " + ha);
        }
    }

    if (remainingChannels.size() == 0) {
        debuglog("Error: could not connect to any of the XMPP DNS SRV records");
        debuglog("Closing attempted TCP sockets");
        for (SocketChannel sc : allChannels.values()) {
            try {
                sc.close();
            } catch (IOException e) {
            }
        }
        debuglog("All attempted TCP sockets are closed now");
        throw new XMPPConfigurationException("Error: could not connect to any of the XMPP DNS SRV records");
    }

    final long starttime = SystemClock.elapsedRealtime();

    HostAddress goodHostAddress = null;
    while (true) {

        Iterator<Entry<HostAddress, SocketChannel>> iter = remainingChannels.entrySet().iterator();
        while (iter.hasNext()) {
            Entry<HostAddress, SocketChannel> e = iter.next();
            final HostAddress ha = e.getKey();
            final SocketChannel sc = e.getValue();
            try {
                if (sc.finishConnect()) {
                    if (sc.isConnected()) {
                        debuglog("Successful TCP connection to " + ha);
                        iter.remove();
                        if (goodHostAddress != null) {
                            // We already found a host
                            // Pick this better one only if the one we found already was not using the
                            // preferred XMPP port, and the new one does have the preferred XMPP port
                            if (goodHostAddress.getPort() != preferredXMPPPort
                                    && ha.getPort() == preferredXMPPPort) {
                                goodHostAddress = ha;
                                debuglog("Found better host " + goodHostAddress);
                            } else {
                                debuglog("Old host was better: " + goodHostAddress);
                            }
                        } else {
                            goodHostAddress = ha;
                            debuglog("Selecting host " + goodHostAddress);
                        }
                    } else {
                        debuglog("Failed TCP connection to " + ha);
                        iter.remove();
                    }
                }
            } catch (IOException ex) {
                // Error during finishConnect()
                debuglog("TCP connection timeout to " + ha);
                iter.remove();
            }
        }

        final long now = SystemClock.elapsedRealtime();
        if (goodHostAddress != null && goodHostAddress.getPort() == preferredXMPPPort) {
            debuglog("Found responsive XMPP host with preferred port " + preferredXMPPPort);
            break;
        }
        if (remainingChannels.size() == 0) {
            debuglog("No more XMPP hosts to check");
            break;
        }
        if (now > starttime + XMPP_MAX_CONNECT_MILLIS) {
            debuglog("Timeout trying to find responsive XMPP host");
            break;
        }
        if (goodHostAddress != null) {
            if (now > starttime + XMPP_MAX_TRY_PREFERRED_PORT_MILLIS) {
                // XXX: would be better to wait at most N seconds (e.g. 2) AFTER the first successful connection
                // happened (to a non preferred port)
                debuglog("Give up looking for responsive XMPP host with preferred port.");
                break;
            }
            boolean stillWaitingForConnectionWithPreferredPort = false;
            for (HostAddress ha : remainingChannels.keySet()) {
                if (ha.getPort() == preferredXMPPPort) {
                    stillWaitingForConnectionWithPreferredPort = true;
                    break;
                }
            }
            if (!stillWaitingForConnectionWithPreferredPort) {
                debuglog("No more responsive XMPP hosts with preferred port to wait for.");
                break;
            }
        }

        debuglog("Sleeping " + XMPP_POLLING_INTERVAL_MILLIS + "ms while trying to connect to XMPP");
        try {
            Thread.sleep(XMPP_POLLING_INTERVAL_MILLIS);
        } catch (InterruptedException ex) {
            throw new XMPPConfigurationException("Interrupt during Thread.sleep()");
        }
    }

    debuglog("Closing attempted TCP sockets");
    for (SocketChannel sc : allChannels.values()) {
        try {
            sc.close();
        } catch (IOException e) {
        }
    }
    debuglog("All attempted TCP sockets are closed now");

    if (goodHostAddress == null) {
        debuglog("Did not find a good host address and hasfailed: " + hasFailed);
        clearSRVConfig();
        if (hasFailed)
            throw new XMPPConfigurationException("Could not connect to any of the XMPP targets");
        else
            return getSafeXmppConnectionConfiguration(xmppServiceName, email, true);
    }

    debuglog("Using XMPP host " + goodHostAddress);
    xmppConfig.setHosts(new HostAddress[] { goodHostAddress });
    return xmppConfig;
}

From source file:com.alexandreroman.nrelay.NmeaRelayService.java

private void sendNmeaOnLocalNetwork(String nmea) throws IOException {
    if (!prefs.getBoolean(SP_NETWORK_READY, false)) {
        Log.d(TAG, "Network is not ready: cannot relay NMEA");
        updateState(State.NETWORK_UNAVAILABLE);
        return;// w  w  w  . j a  v  a 2s . c  o m
    }

    if (sock == null) {
        Log.d(TAG, "Initializing client socket");
        final String hostAddress = prefs.getString(SP_HOST_ADDRESS, "192.168.1.93");
        if (hostAddress == null) {
            throw new IOException("No host address set");
        }
        final int port = Integer.parseInt(prefs.getString(SP_PORT, "0"));
        final InetSocketAddress serverAddr = new InetSocketAddress(hostAddress, port);
        sock = SocketChannel.open();
        sock.configureBlocking(true);
        sock.socket().setSoTimeout(4000);

        Log.d(TAG, "Connecting to server: " + hostAddress + ":" + port);
        try {
            sock.connect(serverAddr);
        } catch (ConnectException e) {
            Log.w(TAG, "Failed to connect to server");
            updateState(State.SERVER_UNREACHABLE);
            sock = null;
            return;
        }
    }

    buffer.clear();
    encoder.encode(CharBuffer.wrap(nmea), buffer, true);
    buffer.flip();

    if (BuildConfig.DEBUG) {
        Log.v(TAG, "Sending NMEA on local network: " + nmea + " (" + buffer.remaining() + " bytes)");
    }
    while (buffer.hasRemaining()) {
        try {
            sock.write(buffer);
        } catch (IOException e) {
            try {
                sock.close();
            } catch (IOException ignore) {
            }
            updateState(State.SERVER_UNREACHABLE);
            sock = null;
            throw e;
        }
    }
    updateState(State.RELAYING_NMEA);
}

From source file:edu.hawaii.soest.pacioos.text.SocketTextSource.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)
*///from   w w w .j a  v a  2  s. c om
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) {

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

}

From source file:org.jenkinsci.remoting.protocol.ProtocolStackLoopbackLoadStress.java

private void startClient(int n, SocketAddress serverAddress, final int clientIntervalMs, boolean ssl)
        throws IOException, ExecutionException, InterruptedException {
    SocketChannel toServer = SocketChannel.open();
    toServer.connect(serverAddress);/*from   www.  j av a  2s. com*/
    SSLEngine sslEngine = context.createSSLEngine();
    sslEngine.setUseClientMode(true);
    final Channel clientChannel = ProtocolStack.on(new NIONetworkLayer(hub, toServer, toServer))
            .named(String.format("Client %d:  %s -> %s", n, toServer.getLocalAddress(), serverAddress))
            .filter(new AckFilterLayer()).filter(ssl ? new SSLEngineFilterLayer(sslEngine, null) : null)
            .filter(new ConnectionHeadersFilterLayer(Collections.singletonMap("id", "client"),
                    new ConnectionHeadersFilterLayer.Listener() {
                        @Override
                        public void onReceiveHeaders(Map<String, String> headers)
                                throws ConnectionRefusalException {

                        }
                    }))
            .build(new ChannelApplicationLayer(executorService, null)).get().get();
    timer[n % timer.length].scheduleAtFixedRate(new TimerTask() {
        private NoOpCallable callable = new NoOpCallable();
        long start = System.currentTimeMillis();
        int times = 0;

        @Override
        public void run() {
            try {
                long start = System.currentTimeMillis();
                clientChannel.call(callable);
                times++;
                if (times % 1000 == 0) {
                    System.out
                            .println(String.format("  %s has run %d No-op callables. Rate %.1f/s expect %.1f/s",
                                    clientChannel.getName(), times,
                                    times * 1000.0 / (System.currentTimeMillis() - this.start),
                                    1000.0 / clientIntervalMs));
                }
                long duration = System.currentTimeMillis() - start;
                if (duration > 250L) {
                    System.err.println(String.format("  %s took %dms to complete a callable",
                            clientChannel.getName(), duration));
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
                IOUtils.closeQuietly(clientChannel);
                cancel();
            }
        }
    }, entropy.nextInt(clientIntervalMs), clientIntervalMs);
}

From source file:org.jenkinsci.remoting.engine.HandlerLoopbackLoadStress.java

private void startClient(int n, SocketAddress serverAddress, final int clientIntervalMs, final int payloadSize)
        throws IOException, ExecutionException, InterruptedException, TimeoutException {
    SocketChannel toServer = SocketChannel.open();
    toServer.socket().setKeepAlive(true);
    toServer.socket().setTcpNoDelay(true);
    toServer.configureBlocking(true);/*w ww  .ja  v  a  2 s  .  c  o  m*/
    toServer.connect(serverAddress);
    HashMap<String, String> headers = new HashMap<String, String>();
    String clientName = runtimeMXBean.getName() + "-client-" + n;
    headers.put(JnlpConnectionState.CLIENT_NAME_KEY, clientName);
    headers.put(JnlpConnectionState.SECRET_KEY, secretFor(clientName));
    final Channel clientChannel = handler.connect(toServer.socket(), headers, clientListener).get(15,
            TimeUnit.SECONDS);
    timer[n % timer.length].scheduleAtFixedRate(new TimerTask() {
        long start = System.currentTimeMillis();
        int index = 0;
        int times = 0;
        private NoOpCallable callable = new NoOpCallable(payloadSize == -1 ? null : new byte[payloadSize]);

        @Override
        public void run() {
            try {
                long start = System.currentTimeMillis();
                clientChannel.call(callable);
                if (config.client != null) {
                    NoOpCallable.noops.incrementAndGet();
                }
                times++;
                if (times % 1000 == 0) {
                    System.out
                            .println(String.format("  %s has run %d No-op callables. Rate %.1f/s expect %.1f/s",
                                    clientChannel.getName(), times,
                                    times * 1000.0 / (System.currentTimeMillis() - this.start),
                                    1000.0 / clientIntervalMs));
                }
                long duration = System.currentTimeMillis() - start;
                if (duration > 250L) {
                    System.err.println(String.format("  %s took %dms to complete a callable",
                            clientChannel.getName(), duration));
                }
                if (callable.payload != null && callable.payload.length > 0) {
                    // mutate the payload to prevent compression
                    int count = callable.payload.length;
                    if (count > 100) {
                        count = 100;
                    }
                    for (int j = 0; j < count; j++) {
                        callable.payload[index] = (byte) (callable.payload[index] * 31 + times);
                        index = Math.abs(index + 1) % callable.payload.length;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace(System.err);
                IOUtils.closeQuietly(clientChannel);
                cancel();
                System.exit(2);
            }
        }
    }, entropy.nextInt(clientIntervalMs), clientIntervalMs);
}

From source file:org.apache.hadoop.dfs.DataNode.java

/**
 * Creates either NIO or regular depending on socketWriteTimeout.
 */// w w w  .j  av  a  2 s .c  o m
private Socket newSocket() throws IOException {
    return (socketWriteTimeout > 0) ? SocketChannel.open().socket() : new Socket();
}

From source file:common.DataNode.java

/**
 * Creates either NIO or regular depending on socketWriteTimeout.
 *///  ww w  .j  a v  a 2s  .  c o  m
protected Socket newSocket() throws IOException {
    return (socketWriteTimeout > 0) ? SocketChannel.open().socket() : new Socket();
}

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)
*/// ww  w.ja v  a 2s  .c  o  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();
        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:org.cloudata.core.commitlog.CommitLogClient.java

private TransactionData[] readDataFrom(Method readMethod, int index, String tabletName) throws IOException {
    int port = -1;
    int replicaCount = rpcUtil.getMultiRpcCount();

    for (int count = 0; count < replicaCount; count++) {
        try {/*from  ww w .jav a 2  s  .  c  o  m*/
            port = (Integer) rpcUtil.singleCall(readMethod, index, tabletName);
            if (port > 0) {
                break;
            }
        } catch (IOException e) {
            LOG.info("Exception in reading commit log data : " + e);
        }

        if (++index % replicaCount == 0) {
            index = 0;
        }
    }

    if (port < 0) {
        return null;
    }

    SocketChannel socketChannel = SocketChannel.open();
    List<TransactionData> txDataList = null;
    try {
        socketChannel.connect(new InetSocketAddress(rpcUtil.getAddressAt(index), port));
        DataInputStream dis = new DataInputStream(
                new BufferedInputStream(socketChannel.socket().getInputStream(), 8192));

        txDataList = readTxDataFrom(tabletName, dis);
    } finally {
        socketChannel.socket().close();
        socketChannel.close();
    }

    return txDataList.toArray(new TransactionData[0]);
}

From source file:edu.hawaii.soest.kilonalu.ctd.SBE37Source.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 w w .j av a 2s.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.configureBlocking(false);
        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;

}