Example usage for java.net Socket connect

List of usage examples for java.net Socket connect

Introduction

In this page you can find the example usage for java.net Socket connect.

Prototype

public void connect(SocketAddress endpoint, int timeout) throws IOException 

Source Link

Document

Connects this socket to the server with a specified timeout value.

Usage

From source file:org.cc86.MMC.client.Main.java

public static void serverDiscoveryHack(String[] args) {
    try {/*from w ww  . ja v a2s  .c o  m*/

        final boolean[] foundSomething = { false };
        List<InetAddress> addrList = new ArrayList<InetAddress>();
        Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
        while (interfaces.hasMoreElements()) {
            try {
                NetworkInterface ifc = (NetworkInterface) interfaces.nextElement();

                if (ifc.isUp()) {
                    Enumeration addresses = ifc.getInetAddresses();
                    while (addresses.hasMoreElements()) {
                        InetAddress addr = (InetAddress) addresses.nextElement();
                        if (addr instanceof Inet6Address) {
                            continue;
                        }
                        byte[] addrraw = addr.getAddress();
                        for (int i = 1; i < 254; i++) {
                            try {
                                final InetAddress calculated = InetAddress.getByAddress(
                                        new byte[] { addrraw[0], addrraw[1], addrraw[2], (byte) i });
                                new Thread(() -> {
                                    //c=new TCPConnection(calculated.getHostAddress(), 0xCC86);
                                    try {
                                        Socket client = new Socket();
                                        client.connect(
                                                new InetSocketAddress(calculated.getHostAddress(), 0xcc87),
                                                2000);
                                        synchronized (foundSomething) {
                                            if (!foundSomething[0]) {
                                                foundSomething[0] = true;
                                                ArrayList<String> lst = new ArrayList(Arrays.asList(args));
                                                lst.add("-i");
                                                lst.add(calculated.getHostAddress());
                                                main(lst.toArray(args));
                                            }
                                        }
                                    } catch (IOException ex) {
                                        //System.out.println(ex.m);
                                        l.trace("Dead host");
                                        //System.exit(0);
                                    }
                                }).start();
                            } catch (UnknownHostException ex) {
                                ex.printStackTrace();
                            }
                        }
                    }
                }
            } catch (SocketException ex) {
                ex.printStackTrace();
            }
        }

    } catch (SocketException ex) {
        ex.printStackTrace();
    }
}

From source file:org.cloudifysource.esc.installer.AgentlessInstaller.java

/*******
 * Checks if a TCP connection to a remote machine and port is possible.
 * /*  w w  w.j av  a2 s.  co m*/
 * @param ip
 *            remote machine ip.
 * @param port
 *            remote machine port.
 * @param installerConfiguration
 *            .
 * @param timeout
 *            duration to wait for successful connection.
 * @param unit
 *            time unit to wait.
 * @throws InstallerException .
 * @throws TimeoutException .
 * @throws InterruptedException .
 */
public static void checkConnection(final String ip, final int port,
        final CloudTemplateInstallerConfiguration installerConfiguration, final long timeout,
        final TimeUnit unit) throws TimeoutException, InterruptedException, InstallerException {

    final long end = System.currentTimeMillis() + unit.toMillis(timeout);

    final InetAddress inetAddress = waitForRoute(installerConfiguration, ip,
            Math.min(end, System.currentTimeMillis()
                    + installerConfiguration.getConnectionTestRouteResolutionTimeoutMillis()));
    final InetSocketAddress socketAddress = new InetSocketAddress(inetAddress, port);

    logger.fine("Checking connection to: " + socketAddress);
    while (System.currentTimeMillis() + installerConfiguration.getConnectionTestIntervalMillis() < end) {

        // need to sleep since sock.connect may return immediately, and
        // server may take time to start
        Thread.sleep(installerConfiguration.getConnectionTestIntervalMillis());

        final Socket sock = new Socket();
        try {
            sock.connect(socketAddress, installerConfiguration.getConnectionTestConnectTimeoutMillis());
            return;
        } catch (final IOException e) {
            logger.log(Level.FINE, "Checking connection to: " + socketAddress, e);
            // retry
        } finally {
            if (sock != null) {
                try {
                    sock.close();
                } catch (final IOException e) {
                    logger.fine("Failed to close socket");
                }
            }
        }
    }

    //timeout was reached
    String ipAddress = inetAddress.getHostAddress(); //if resolving fails we don't reach this line
    throw new TimeoutException("Failed connecting to " + IPUtils.getSafeIpAddress(ipAddress) + ":" + port);

}

From source file:gridool.util.net.SocketUtils.java

/**
 * @param connectTimeout A timeout of zero is interpreted as an infinite timeout.
 * @param pollDelay sleep in mills before retry.
 * @param maxRetry No-retry if the value is 1.
 *//*w  ww  .j  av  a 2 s .  c  om*/
public static Socket openSocket(Socket socket, SocketAddress sockAddr, int connectTimeout, long pollDelay,
        int maxRetry) throws IOException {
    assert (sockAddr != null);
    assert (pollDelay >= 0) : pollDelay;
    assert (maxRetry > 0) : maxRetry;
    for (int i = 0; i < maxRetry; i++) {
        try {
            socket.connect(sockAddr, connectTimeout);
        } catch (SocketTimeoutException ste) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Socket.connect to " + sockAddr + " timeout #" + (i + 1));
            }
        } catch (IOException e) {
            if (LOG.isWarnEnabled()) {
                LOG.warn("Socket.connect to " + sockAddr + " failed #" + (i + 1), e);
            }
        } catch (Throwable e) {
            LOG.fatal("failed to connect: " + sockAddr, e);
            throw new IOException(e);
        }
        if (socket.isConnected()) {
            return socket;
        }
        if (pollDelay > 0) {
            try {
                Thread.sleep(pollDelay);
            } catch (InterruptedException ie) {
                ;
            }
        }
    }
    throw new InterruptedIOException("Could not connect to " + sockAddr);
}

From source file:net.grinder.util.NetworkUtils.java

public static boolean tryConnection(String byConnecting, int port, Socket socket) {
    try {//from   w  w w .j  av a  2 s.  co m
        socket.connect(new InetSocketAddress(byConnecting, port), 2000); // 2 seconds timeout
    } catch (Exception e) {
        return false;
    }
    return true;
}

From source file:org.planetcrypto.bitcoin.PlanetCryptoBitcoinMinerAPICommands.java

private static String process(String cmd, InetSocketAddress ip, int port) throws Exception {
    Socket socket = new Socket();
    StringBuffer sb = new StringBuffer();
    char buf[] = new char[MAXRECEIVESIZE];
    int len = 0;/* w w  w.java  2 s  .  c  o  m*/
    //System.out.println("Attempting to send: " + cmd + " to: "+ ip.getHostAddress()+":"+port);
    try {
        //socket = new Socket(ip, port);
        socket.connect(ip, 2000);
        //System.out.println("Start Sleep");
        //Thread.sleep(1000);
        //System.out.println("Stop Sleep");
        socket.setSoTimeout(2000);
        //socket.(ip, port);
        //System.out.println(socket.getSoTimeout());
        PrintStream ps = new PrintStream(socket.getOutputStream());
        ps.print(cmd.toLowerCase().toCharArray());
        InputStreamReader isr = new InputStreamReader(socket.getInputStream());
        while (0x80085 > 0) {
            len = isr.read(buf, 0, MAXRECEIVESIZE);
            if (len < 1) {
                break;
            }
            sb.append(buf, 0, len);
            if (buf[len - 1] == '\0') {
                break;
            }
        }
        //closeAll();
        socket.close();
        socket = null;
    } catch (IOException ioe) {
        System.err.println(ioe.toString() + ", " + ip.getHostName());
        //closeAll();
        socket.close();
        socket = null;
        return "Failed to get information";
    }
    String result = sb.toString();
    //System.out.println(result);
    return result.replace("\0", "");
    //jsonFactory(result);
    //System.out.println(result);
}

From source file:hu.netmind.beankeeper.node.impl.NodeManagerImpl.java

/**
 * Determine if an address is available.
 *///from   www .j av a 2  s  .co  m
public static boolean isAlive(String ips, int port) {
    if (logger.isDebugEnabled())
        logger.debug("trying to reach: " + ips + ":" + port);
    try {
        if ("".equals(ips))
            ips = InetAddress.getLocalHost().getHostAddress();
    } catch (Exception e) {
        throw new StoreException(
                "can not determine local adapter, but there is another node, which would need to be contacted.",
                e);
    }
    StringTokenizer tokens = new StringTokenizer(ips, ",");
    while (tokens.hasMoreTokens()) {
        String ip = tokens.nextToken();
        if (logger.isDebugEnabled())
            logger.debug("determining whether '" + ip + ":" + port + "' is alive...");
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(ip, port), SOCKET_CONNECT_TIMEOUT);
            socket.close();
            return true; // Success, so return true
        } catch (Exception e) {
            logger.debug("unreachable node at '" + ip + ":" + port + ", " + e.getMessage());
        }
    }
    logger.debug("could not reach any of the ips given for node");
    return false;
}

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

public static void connect(Socket socket, SocketAddress endpoint, int timeout) throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }/*  w w  w.  j a va2s. c o  m*/

    SocketChannel ch = socket.getChannel();

    if (ch == null) {
        // let the default implementation handle it.
        socket.connect(endpoint, timeout);
    } else {
        SocketIOWithTimeout.connect(ch, endpoint, timeout);
    }
}

From source file:SocketFetcher.java

/**
 * Create a socket with the given local address and connected to
 * the given host and port.  Use the specified connection timeout.
 * If a socket factory is specified, use it.  Otherwise, use the
 * SSLSocketFactory if useSSL is true./*  w  w  w  . j  a v a 2 s  .  c  o m*/
 */
private static Socket createSocket(InetAddress localaddr, int localport, String host, int port, int cto,
        SocketFactory sf, boolean useSSL) throws IOException {
    Socket socket;

    if (sf != null)
        socket = sf.createSocket();
    else if (useSSL)
        socket = SSLSocketFactory.getDefault().createSocket();
    else
        socket = new Socket();
    if (localaddr != null)
        socket.bind(new InetSocketAddress(localaddr, localport));
    if (cto >= 0)
        socket.connect(new InetSocketAddress(host, port), cto);
    else
        socket.connect(new InetSocketAddress(host, port));
    return socket;
}

From source file:org.apache.hadoop.hdfs.server.blockmanagement.TestBlockTokenWithDFS.java

private static void tryRead(final Configuration conf, LocatedBlock lblock, boolean shouldSucceed) {
    InetSocketAddress targetAddr = null;
    IOException ioe = null;//from ww  w  . ja v a2s .  c o m
    BlockReader blockReader = null;
    ExtendedBlock block = lblock.getBlock();
    try {
        DatanodeInfo[] nodes = lblock.getLocations();
        targetAddr = NetUtils.createSocketAddr(nodes[0].getXferAddr());

        blockReader = new BlockReaderFactory(new DFSClient.Conf(conf))
                .setFileName(BlockReaderFactory.getFileName(targetAddr, "test-blockpoolid", block.getBlockId()))
                .setExtendedBlock(block).setBlockToken(lblock.getBlockToken()).setInetSocketAddress(targetAddr)
                .setStartOffset(0).setLength(-1).setVerifyChecksum(true).setClientName("TestBlockTokenWithDFS")
                .setDatanodeInfo(nodes[0]).setCachingStrategy(CachingStrategy.newDefaultStrategy())
                .setClientCacheContext(ClientContext.getFromConf(conf)).setConfiguration(conf)
                .setTracer(FsTracer.get(conf)).setRemotePeerFactory(new RemotePeerFactory() {
                    @Override
                    public SocketFactory getSocketFactory(Configuration conf) throws IOException {
                        return NetUtils.getDefaultSocketFactory(conf);
                    }

                    @Override
                    public Peer newConnectedPeer(InetSocketAddress addr, Token<BlockTokenIdentifier> blockToken,
                            DatanodeID datanodeId) throws IOException {
                        Peer peer = null;
                        Socket sock = getSocketFactory(conf).createSocket();
                        try {
                            sock.connect(addr, HdfsServerConstants.READ_TIMEOUT);
                            sock.setSoTimeout(HdfsServerConstants.READ_TIMEOUT);
                            peer = TcpPeerServer.peerFromSocket(sock);
                        } finally {
                            if (peer == null) {
                                IOUtils.closeSocket(sock);
                            }
                        }
                        return peer;
                    }
                }).build();
    } catch (IOException ex) {
        ioe = ex;
    } finally {
        if (blockReader != null) {
            try {
                blockReader.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    if (shouldSucceed) {
        Assert.assertNotNull("OP_READ_BLOCK: access token is invalid, " + "when it is expected to be valid",
                blockReader);
    } else {
        Assert.assertNotNull("OP_READ_BLOCK: access token is valid, " + "when it is expected to be invalid",
                ioe);
        Assert.assertTrue("OP_READ_BLOCK failed due to reasons other than access token: ",
                ioe instanceof InvalidBlockTokenException);
    }
}

From source file:org.cloudifysource.dsl.utils.IPUtils.java

/**
 * Validates a connection can be made to the given address and port, within
 * the given time limit./*from   w  w w . j a  va  2s. co  m*/
 * 
 * @param ipAddress
 *            The IP address to connect to
 * @param port
 *            The port number to use
 * @param timeout
 *            The time to wait before timing out, in seconds
 * @throws IOException
 *             Reports a failure to connect or resolve the given address.
 */
public static void validateConnection(final String ipAddress, final int port, final int timeout)
        throws IOException {

    final Socket socket = new Socket();

    try {
        final InetSocketAddress endPoint = new InetSocketAddress(ipAddress, port);
        if (endPoint.isUnresolved()) {
            throw new UnknownHostException(ipAddress);
        }

        socket.connect(endPoint, safeLongToInt(TimeUnit.SECONDS.toMillis(timeout), true));
    } finally {
        try {
            socket.close();
        } catch (final IOException ioe) {
            // ignore
        }
    }
}