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.imogene.client.ssl.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>/*from w  ww  .  ja va 2s . c o m*/
 * To circumvent the limitations of older JREs that do not support connect timeout a controller thread is executed. The
 * controller thread attempts to create a new socket within the given limit of time. If socket constructor does not return
 * until the timeout expires, the controller terminates and throws an {@link ConnectTimeoutException}
 * </p>
 * 
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be determined
 */
@Override
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null"); //$NON-NLS-1$
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:in.mycp.remote.InfraService.java

@RemoteMethod
public String getInfraStatusDWR(int infraId) {
    Infra infra = Infra.findInfra(infraId);
    String status = Commons.EUCA_STATUS.unknown + "";
    try {/*  w w  w.j ava  2  s .  co m*/
        //first , just try to reach and ping the server, then try connecting
        try {
            InetAddress byIpAsName = InetAddress.getByName(infra.getServer());
            SocketAddress sockaddr = new InetSocketAddress(byIpAsName, infra.getPort());
            Socket theSock = new Socket();
            theSock.connect(sockaddr, 4000);
        } catch (Exception e) {
            //log.error(e.getMessage());//e.printStackTrace();
            log.error(e);
            status = Commons.EUCA_STATUS.unreachable + "";
            log.info("Cant even open socket to server " + infra.getServer() + ".wont try to connect!");
            throw new Exception(
                    "Cant even open socket to server " + infra.getServer() + ".wont try to connect!");
        }

        BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
        textEncryptor.setPassword("gothilla");
        String decAccessId = textEncryptor.decrypt(infra.getAccessId());
        String decSecretKey = textEncryptor.decrypt(infra.getSecretKey());

        Jec2 ec2 = new Jec2(decAccessId, decSecretKey, false, infra.getServer(), infra.getPort());
        if (infra.getServer() != null && !infra.getServer().contains("ec2.amazonaws.com")) {
            ec2.setResourcePrefix(infra.getResourcePrefix());
            ec2.setSignatureVersion(infra.getSignatureVersion());
            ec2.setMaxRetries(1);
        }

        List params = new ArrayList<String>();

        List<RegionInfo> regions = ec2.describeRegions(params);
        for (Iterator iterator = regions.iterator(); iterator.hasNext();) {
            RegionInfo regionInfo = (RegionInfo) iterator.next();
            if (regionInfo != null) {
                status = Commons.EUCA_STATUS.running + "";
            } else if (regionInfo == null) {
                status = Commons.EUCA_STATUS.error + "";
            }
            break;
        }
    } catch (Exception e) {
        log.error(e.getMessage());
        //e.printStackTrace();
        log.error(e);
        if (e.getMessage() != null && e.getMessage().indexOf("Client error") > -1) {
            status = Commons.EUCA_STATUS.running + "";
        } else if (e.getMessage() != null && e.getMessage().indexOf("Cant even open socket") > -1) {
            status = Commons.EUCA_STATUS.unreachable + "";
        } else {
            status = Commons.EUCA_STATUS.unknown + "";
        }
    }
    //System.out.println(" = ssssssssssssssssssssssssssssssss ");
    return infra.getServer() + "=" + status;
}

From source file:com.predic8.membrane.core.transport.ssl.SSLContext.java

public Socket createSocket(InetAddress host, int port, int connectTimeout) throws IOException {
    Socket s = new Socket();
    s.connect(new InetSocketAddress(host, port), connectTimeout);
    SSLSocketFactory sslsf = sslc.getSocketFactory();
    SSLSocket ssls = (SSLSocket) sslsf.createSocket(s, host.getHostName(), port, true);
    if (protocols != null) {
        ssls.setEnabledProtocols(protocols);
    } else {//w  w  w. ja va2 s. c om
        String[] protocols = ssls.getEnabledProtocols();
        Set<String> set = new HashSet<String>();
        for (String protocol : protocols) {
            if (protocol.equals("SSLv3") || protocol.equals("SSLv2Hello")) {
                continue;
            }
            set.add(protocol);
        }
        ssls.setEnabledProtocols(set.toArray(new String[0]));
    }
    applyCiphers(ssls);
    return ssls;
}

From source file:com.fatwire.dta.sscrawler.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from  w  ww .  j  av  a 2  s  .  c o m
 * <p>
 * To circumvent the limitations of older JREs that do not support connect
 * timeout a controller thread is executed. The controller thread attempts
 * to create a new socket within the given limit of time. If socket
 * constructor does not return until the timeout expires, the controller
 * terminates and throws an {@link ConnectTimeoutException}
 * </p>
 * 
 * @param host the host name/IP
 * @param port the port on the host
 * @param localAddress the local host name/IP to bind the socket to
 * @param localPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be
 *             determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    final int timeout = params.getConnectionTimeout();
    final SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        final Socket socket = socketfactory.createSocket();
        final SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        final SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:com.ephesoft.dcma.batch.service.EphesoftSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>//from w ww. j ava  2 s. c  o m
 * To circumvent the limitations of older JREs that do not support connect timeout a controller thread is executed. The controller
 * thread attempts to create a new socket within the given limit of time. If socket constructor does not return until the timeout
 * expires, the controller terminates and throws an {@link ConnectTimeoutException}
 * </p>
 * 
 * @param host the host name/IP
 * @param port the port on the host
 * @param clientHost the local host name/IP to bind the socket to
 * @param clientPort the port on the local machine
 * @param params {@link HttpConnectionParams Http connection parameters}
 * 
 * @return Socket a new socket
 * 
 * @throws IOException if an I/O error occurs while creating the socket
 * @throws UnknownHostException if the IP address of the host cannot be determined
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params) throws IOException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    final int timeout = params.getConnectionTimeout();
    final SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        final Socket socket = socketfactory.createSocket();
        final SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        final SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:com.thoughtworks.go.security.AuthSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>/*from   w w  w .ja  v a2  s . com*/
 * To circumvent the limitations of older JREs that do not support connect timeout a
 * controller thread is executed. The controller thread attempts to create a new socket
 * within the given limit of time. If socket constructor does not return until the
 * timeout expires, the controller terminates and throws an
 * {@link org.apache.commons.httpclient.ConnectTimeoutException}
 * </p>
 *
 * @param host   the host name/IP
 * @param port   the port on the host
 * @param params {@link HttpConnectionParams Http connection parameters}
 * @return Socket a new socket
 * @throws IOException if an I/O error occurs while creating the socket
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params) throws IOException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    if (timeout == 0) {
        return socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
        return socket;
    }
}

From source file:org.apache.hadoop.hive.metastore.utils.MetaStoreServerUtils.java

/**
 * A simple connect test to make sure that the metastore is up
 * @throws Exception/*  w  w  w. j av  a 2s  . c o m*/
 */
private static void loopUntilHMSReady(int port) throws Exception {
    int retries = 0;
    Exception exc;
    while (true) {
        try {
            Socket socket = new Socket();
            socket.connect(new InetSocketAddress(port), 5000);
            socket.close();
            return;
        } catch (Exception e) {
            if (retries++ > 60) { //give up
                exc = e;
                break;
            }
            Thread.sleep(1000);
        }
    }
    // something is preventing metastore from starting
    // print the stack from all threads for debugging purposes
    LOG.error("Unable to connect to metastore server: " + exc.getMessage());
    LOG.info("Printing all thread stack traces for debugging before throwing exception.");
    LOG.info(getAllThreadStacksAsString());
    throw exc;
}

From source file:net.timewalker.ffmq4.transport.tcp.io.TcpPacketTransport.java

/**
 * Connect the transport to its remote endpoint
 *///  w w  w .  java 2 s .  c  o m
private Socket connect(URI transportURI) throws PacketTransportException {
    String protocol = transportURI.getScheme();
    String host = transportURI.getHost();
    int port = transportURI.getPort();
    int connectTimeout = settings.getIntProperty(FFMQClientSettings.TRANSPORT_TCP_CONNECT_TIMEOUT, 30);

    try {
        Socket socket = SocketUtils.setupSocket(createSocket(protocol), socketSendBufferSize,
                socketRecvBufferSize);

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

        return socket;
    } catch (ConnectException e) {
        log.error("#" + id + " could not connect to " + host + ":" + port + " (timeout=" + connectTimeout
                + "s) : " + e.getMessage());
        throw new PacketTransportException("Could not connect to " + host + ":" + port + " : " + e.toString());
    } catch (Exception e) {
        log.error(
                "#" + id + " could not connect to " + host + ":" + port + " (timeout=" + connectTimeout + "s)",
                e);
        throw new PacketTransportException("Could not connect to " + host + ":" + port + " : " + e.toString());
    }
}

From source file:org.apache.usergrid.chop.client.ssh.Job.java

protected boolean waitActive(int timeout) {
    LOG.info("Waiting maximum {} msecs for SSH port of {} to get active", timeout, value.getPublicIpAddress());
    long startTime = System.currentTimeMillis();

    while (System.currentTimeMillis() - startTime < timeout) {
        Socket s = null;
        try {// ww  w.  j a  v a2  s  .  c o  m
            s = new Socket();
            s.setReuseAddress(true);
            SocketAddress sa = new InetSocketAddress(value.getPublicIpAddress(), 22);
            s.connect(sa, 2000);
            LOG.info("Port 22 of {} got opened", value.getPublicIpAddress());
            return true;
        } catch (Exception e) {
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ee) {
            }
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException e) {
                }
            }
        }
    }
    return false;
}

From source file:com.smartwork.client.gsocket.CommonSocketFactory.java

public Object makeObject(Object key) throws Exception {
    ServerAddress address = (ServerAddress) key;
    Socket conn = new Socket();
    conn.setSoTimeout(networkConfig.getReadTimeout() * 1000);
    conn.setTcpNoDelay(networkConfig.isTcpNoDelay());
    conn.setReuseAddress(networkConfig.isReuseAddress());
    conn.setSoLinger(networkConfig.getSoLinger() > 0, networkConfig.getSoLinger());
    conn.setSendBufferSize(networkConfig.getSendBufferSize());
    conn.setReceiveBufferSize(networkConfig.getReceiveBufferSize());
    conn.connect(new InetSocketAddress(address.getHost(), address.getPort()),
            networkConfig.getConnectTimeout() * 1000);
    return conn;/*  ww  w .j a v a2s .  co m*/
}