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:cn.org.eshow.framwork.http.ssl.AuthSSLProtocolSocketFactory.java

/***
 * Attempts to get a new socket connection to the given host within the
 * given time limit./*from  w  w  w. j  a v 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 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");
    }
    int timeout = AbHttpClient.DEFAULT_SOCKET_TIMEOUT;
    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.pluroid.pluroium.HttpClientFactory.java

public Socket connectSocket(Socket socket, String host, int port, InetAddress localAddress, int localPort,
        HttpParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    if (socket == null) {
        socket = createSocket();/*ww w . j  a v  a  2  s . c om*/
    }
    if ((localAddress != null) || (localPort > 0)) {
        if (localPort < 0) {
            localPort = 0; // indicates "any"
        }
        socket.bind(new InetSocketAddress(localAddress, localPort));
    }
    socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
    socket.connect(new InetSocketAddress(host, port), HttpConnectionParams.getConnectionTimeout(params));
    return socket;
}

From source file:it.greenvulcano.gvesb.http.ssl.AuthSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the
 * given time limit.//from  w ww  .ja  v a 2 s .co 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
 * @throws ConnectTimeoutException
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    try {
        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);
        }

        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;
    } catch (UnknownHostException exc) {
        logger.error("UnknownHostException connecting to host", exc);
        throw exc;
    } catch (ConnectTimeoutException exc) {
        logger.error("ConnectTimeoutException connecting to host", exc);
        throw exc;
    } catch (IOException exc) {
        logger.error("IOException connecting to host", exc);
        throw exc;
    }
}

From source file:com.owncloud.android.lib.common.network.AdvancedSslSocketFactory.java

/**
  * Attempts to get a new socket connection to the given host within the
  * given time limit./*from  w w w .j  a  va2s. com*/
  * 
  * @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, UnknownHostException, ConnectTimeoutException {
    Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();

    //logSslInfo();

    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    enableSecureProtocols(socket);
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
}

From source file:com.cerema.cloud2.lib.common.network.AdvancedSslSocketFactory.java

/**
  * Attempts to get a new socket connection to the given host within the
  * given time limit./* w w  w  .  j  a  v  a 2s.  co  m*/
  * 
  * @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 {
    Log_OC.d(TAG, "Creating SSL Socket with remote " + host + ":" + port + ", local " + localAddress + ":"
            + localPort + ", params: " + params);
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();

    //logSslInfo();

    SocketFactory socketfactory = mSslContext.getSocketFactory();
    Log_OC.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    enableSecureProtocols(socket);
    SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
    SocketAddress remoteaddr = new InetSocketAddress(host, port);
    socket.setSoTimeout(params.getSoTimeout());
    socket.bind(localaddr);
    ServerNameIndicator.setServerNameIndication(host, (SSLSocket) socket);
    socket.connect(remoteaddr, timeout);
    verifyPeerIdentity(host, port, socket);
    return socket;
}

From source file:com.zimbra.cs.mailclient.MailConnection.java

private Socket newSocket() throws IOException {
    SocketFactory sf = config.getSecurity() != MailConfig.Security.SSL ? getSocketFactory()
            : getSSLSocketFactory();//  w  w  w.j a v  a  2  s  .com
    Socket sock = sf.createSocket();
    int connectTimeout = (int) Math.min(config.getConnectTimeout() * 1000L, Integer.MAX_VALUE);
    int readTimeout = (int) Math.min(config.getReadTimeout() * 1000L, Integer.MAX_VALUE);
    sock.setSoTimeout(readTimeout > 0 ? readTimeout : Integer.MAX_VALUE);
    sock.connect(new InetSocketAddress(config.getHost(), config.getPort()),
            connectTimeout > 0 ? connectTimeout : Integer.MAX_VALUE);
    return sock;
}

From source file:password.pwm.http.servlet.configguide.ConfigGuideServlet.java

private void checkLdapServer(final ConfigGuideBean configGuideBean)
        throws PwmOperationalException, IOException {
    final Map<ConfigGuideFormField, String> formData = configGuideBean.getFormData();
    final String host = formData.get(ConfigGuideFormField.PARAM_LDAP_HOST);
    final int port = Integer.parseInt(formData.get(ConfigGuideFormField.PARAM_LDAP_PORT));

    { // socket test
        final InetAddress inetAddress = InetAddress.getByName(host);
        final SocketAddress socketAddress = new InetSocketAddress(inetAddress, port);
        final Socket socket = new Socket();

        final int timeout = 2000;
        socket.connect(socketAddress, timeout);
    }//w w  w . jav a2s .co m

    if (Boolean.parseBoolean(formData.get(ConfigGuideFormField.PARAM_LDAP_SECURE))) {
        X509Utils.readRemoteCertificates(host, port);
    }
}

From source file:com.mirth.connect.server.util.ConnectorUtil.java

public static ConnectionTestResponse testConnection(String host, int port, int timeout, String localAddr,
        int localPort) throws Exception {
    Socket socket = null;
    InetSocketAddress address = null;
    InetSocketAddress localAddress = null;

    try {/*from w w  w .  j ava  2 s . c o m*/
        address = new InetSocketAddress(host, port);

        if (StringUtils.isBlank(address.getAddress().getHostAddress()) || (address.getPort() < 0)
                || (address.getPort() > 65534)) {
            throw new Exception();
        }
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Invalid host or port.");
    }

    if (localAddr != null) {
        try {
            localAddress = new InetSocketAddress(localAddr, localPort);

            if (StringUtils.isBlank(localAddress.getAddress().getHostAddress()) || (localAddress.getPort() < 0)
                    || (localAddress.getPort() > 65534)) {
                throw new Exception();
            }
        } catch (Exception e) {
            return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                    "Invalid local host or port.");
        }
    }

    try {
        socket = new Socket();

        if (localAddress != null) {
            try {
                socket.bind(localAddress);
            } catch (Exception e) {
                return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE,
                        "Could not bind to local address: " + localAddress.getAddress().getHostAddress() + ":"
                                + localAddress.getPort());
            }
        }

        socket.connect(address, timeout);
        String connectionInfo = socket.getLocalAddress().getHostAddress() + ":" + socket.getLocalPort() + " -> "
                + address.getAddress().getHostAddress() + ":" + address.getPort();
        return new ConnectionTestResponse(ConnectionTestResponse.Type.SUCCESS,
                "Successfully connected to host: " + connectionInfo, connectionInfo);
    } catch (SocketTimeoutException ste) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.TIME_OUT, "Timed out connecting to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } catch (Exception e) {
        return new ConnectionTestResponse(ConnectionTestResponse.Type.FAILURE, "Could not connect to host: "
                + address.getAddress().getHostAddress() + ":" + address.getPort());
    } finally {
        if (socket != null) {
            socket.close();
        }
    }
}

From source file:com.clustercontrol.notify.util.SendSyslog.java

private void sendTcpMsg(InetAddress ipAddress, int port, String msg) throws IOException {

    Socket socket = null;
    OutputStream os = null;//w ww . j a  va2s  .co  m
    PrintWriter writer = null;
    try {
        InetSocketAddress endpoint = new InetSocketAddress(ipAddress, port);
        socket = new Socket();
        socket.connect(endpoint,
                HinemosPropertyUtil.getHinemosPropertyNum(PROP_TCP_TIMEOUT, Long.valueOf(3000)).intValue());

        os = socket.getOutputStream();
        writer = new PrintWriter(socket.getOutputStream(), true);
        writer.println(msg);
        writer.flush();
    } finally {
        if (writer != null) {
            writer.close();
        }
        if (os != null) {
            os.close();
        }
        if (socket != null) {
            socket.close();
        }
    }
}