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.apache.hadoop.hdfs.server.namenode.JspHelper.java

public void streamBlockInAscii(InetSocketAddress addr, long blockId, Token<BlockTokenIdentifier> accessToken,
        long genStamp, long blockSize, long offsetIntoBlock, long chunkSizeToView, JspWriter out,
        Configuration conf) throws IOException {
    if (chunkSizeToView == 0)
        return;/*ww  w  .j  a v a2 s .  c  o m*/
    Socket s = new Socket();
    s.connect(addr, HdfsConstants.READ_TIMEOUT);
    s.setSoTimeout(HdfsConstants.READ_TIMEOUT);

    long amtToRead = Math.min(chunkSizeToView, blockSize - offsetIntoBlock);

    // Use the block name for file name. 
    DFSClient.BlockReader blockReader = DFSClient.BlockReader.newBlockReader(s, addr.toString() + ":" + blockId,
            blockId, accessToken, genStamp, offsetIntoBlock, amtToRead,
            conf.getInt("io.file.buffer.size", 4096));

    byte[] buf = new byte[(int) amtToRead];
    int readOffset = 0;
    int retries = 2;
    while (amtToRead > 0) {
        int numRead;
        try {
            numRead = blockReader.readAll(buf, readOffset, (int) amtToRead);
        } catch (IOException e) {
            retries--;
            if (retries == 0)
                throw new IOException("Could not read data from datanode");
            continue;
        }
        amtToRead -= numRead;
        readOffset += numRead;
    }
    blockReader = null;
    s.close();
    out.print(HtmlQuoting.quoteHtmlChars(new String(buf)));
}

From source file:com.buaa.cfs.utils.NetUtils.java

/**
 * Like {@link NetUtils#connect(Socket, SocketAddress, int)} but also takes a local address and port to bind the
 * socket to./*from  www.  j  a v a2s .  com*/
 *
 * @param socket
 * @param endpoint  the remote address
 * @param localAddr the local address to bind the socket to
 * @param timeout   timeout in milliseconds
 */
public static void connect(Socket socket, SocketAddress endpoint, SocketAddress localAddr, int timeout)
        throws IOException {
    if (socket == null || endpoint == null || timeout < 0) {
        throw new IllegalArgumentException("Illegal argument for connect()");
    }

    SocketChannel ch = socket.getChannel();

    if (localAddr != null) {
        Class localClass = localAddr.getClass();
        Class remoteClass = endpoint.getClass();
        Preconditions.checkArgument(localClass.equals(remoteClass),
                "Local address %s must be of same family as remote address %s.", localAddr, endpoint);
        socket.bind(localAddr);
    }

    try {
        if (ch == null) {
            // let the default implementation handle it.
            socket.connect(endpoint, timeout);
        } else {
            //        SocketIOWithTimeout.connect(ch, endpoint, timeout);
        }
    } catch (SocketTimeoutException ste) {
        //      throw new ConnectTimeoutException(ste.getMessage());
    }

    // There is a very rare case allowed by the TCP specification, such that
    // if we are trying to connect to an endpoint on the local machine,
    // and we end up choosing an ephemeral port equal to the destination port,
    // we will actually end up getting connected to ourself (ie any data we
    // send just comes right back). This is only possible if the target
    // daemon is down, so we'll treat it like connection refused.
    if (socket.getLocalPort() == socket.getPort() && socket.getLocalAddress().equals(socket.getInetAddress())) {
        LOG.info("Detected a loopback TCP socket, disconnecting it");
        socket.close();
        throw new ConnectException("Localhost targeted connection resulted in a loopback. "
                + "No daemon is listening on the target port.");
    }
}

From source file:processing.app.debug.EasySSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>/*from   w w  w. j a  v a 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, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = getSSLContext().getSocketFactory();
    Socket socket;
    if (timeout == 0) {
        socket = socketfactory.createSocket(host, port, localAddress, localPort);
    } else {
        socket = socketfactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
    }

    SSLSocket sslSocket = (SSLSocket) socket;
    sslSocket.setEnabledProtocols(SSL_PROTOCOLS);
    sslSocket.setEnabledCipherSuites(SSL_CYPHER_SUITES);

    return socket;
}

From source file:org.apache.commons.httpclient.contrib.ssl.AuthSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 * <p>//w  w  w .j a v a  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
 */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }
    int timeout = HttpConnectionParams.getConnectionTimeout(params);
    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:com.adito.server.ServerLock.java

private void checkStatus() {
    Socket socket = null;
    try {//from   w ww  . j  a v  a2  s  .  co m
        int timeout = 5000; // 5 seconds
        if (log.isInfoEnabled())
            log.info("Connecting to " + bindAddress + ":" + port + " to see if a server is already running.");
        SocketAddress socketAddress = new InetSocketAddress(bindAddress, port);
        socket = new Socket();
        socket.connect(socketAddress, timeout);
        locked = true;
    } catch (Exception e) {
        locked = false;
    } finally {
        if (socket != null) {
            try {
                socket.close();
            } catch (Exception e) {

            }
        }
    }
}

From source file:org.apache.jmeter.util.HttpSSLProtocolSocketFactory.java

/**
 * Attempts to get a new socket connection to the given host within the given time limit.
 *
 * @param host the host name/IP/*from  ww w . j  a va2s. c  om*/
 * @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
 */
@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");
    }
    int timeout = params.getConnectionTimeout();

    SSLSocketFactory sslfac = getSSLSocketFactory();
    Socket socket;
    if (timeout == 0) {
        socket = sslfac.createSocket(host, port, localAddress, localPort);
    } else {
        socket = sslfac.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        socket.bind(localaddr);
        socket.connect(remoteaddr, timeout);
    }
    setSocket(socket);
    return wrapSocket(socket);
}

From source file:com.klinker.android.twitter.utils.api_helper.TwitterMultipleImageHelper.java

public boolean uploadPics(File[] pics, String text, Twitter twitter) {
    JSONObject jsonresponse = new JSONObject();

    final String ids_string = getMediaIds(pics, twitter);

    if (ids_string == null) {
        return false;
    }/*from   w ww . ja v a 2 s .c  om*/

    try {
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "POST";
        String oauth_signature_method = "HMAC-SHA1";

        String uuid_string = UUID.randomUUID().toString();
        uuid_string = uuid_string.replaceAll("-", "");
        String oauth_nonce = uuid_string; // any relatively random alphanumeric string will work here

        // get the timestamp
        Calendar tempcal = Calendar.getInstance();
        long ts = tempcal.getTimeInMillis();// get current time in milliseconds
        String oauth_timestamp = (new Long(ts / 1000)).toString(); // then divide by 1000 to get seconds

        // the parameter string must be in alphabetical order, "text" parameter added at end
        String parameter_string = "oauth_consumer_key=" + AppSettings.TWITTER_CONSUMER_KEY + "&oauth_nonce="
                + oauth_nonce + "&oauth_signature_method=" + oauth_signature_method + "&oauth_timestamp="
                + oauth_timestamp + "&oauth_token=" + encode(oauth_token) + "&oauth_version=1.0";
        System.out.println("Twitter.updateStatusWithMedia(): parameter_string=" + parameter_string);

        String twitter_endpoint = "https://api.twitter.com/1.1/statuses/update.json";
        String twitter_endpoint_host = "api.twitter.com";
        String twitter_endpoint_path = "/1.1/statuses/update.json";
        String signature_base_string = get_or_post + "&" + encode(twitter_endpoint) + "&"
                + encode(parameter_string);
        String oauth_signature = computeSignature(signature_base_string,
                AppSettings.TWITTER_CONSUMER_SECRET + "&" + encode(oauth_token_secret));

        String authorization_header_string = "OAuth oauth_consumer_key=\"" + AppSettings.TWITTER_CONSUMER_KEY
                + "\",oauth_signature_method=\"HMAC-SHA1\",oauth_timestamp=\"" + oauth_timestamp
                + "\",oauth_nonce=\"" + oauth_nonce + "\",oauth_version=\"1.0\",oauth_signature=\""
                + encode(oauth_signature) + "\",oauth_token=\"" + encode(oauth_token) + "\"";

        HttpParams params = new BasicHttpParams();
        HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
        HttpProtocolParams.setContentCharset(params, "UTF-8");
        HttpProtocolParams.setUserAgent(params, "HttpCore/1.1");
        HttpProtocolParams.setUseExpectContinue(params, false);
        HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
                // Required protocol interceptors
                new RequestContent(), new RequestTargetHost(),
                // Recommended protocol interceptors
                new RequestConnControl(), new RequestUserAgent(), new RequestExpectContinue() });

        HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
        HttpContext context = new BasicHttpContext(null);
        HttpHost host = new HttpHost(twitter_endpoint_host, 443);
        DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

        context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
        context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);

        try {
            try {
                SSLContext sslcontext = SSLContext.getInstance("TLS");
                sslcontext.init(null, null, null);
                SSLSocketFactory ssf = sslcontext.getSocketFactory();
                Socket socket = ssf.createSocket();
                socket.connect(new InetSocketAddress(host.getHostName(), host.getPort()), 0);
                conn.bind(socket, params);
                BasicHttpEntityEnclosingRequest request2 = new BasicHttpEntityEnclosingRequest("POST",
                        twitter_endpoint_path);

                MultipartEntity reqEntity = new MultipartEntity();
                reqEntity.addPart("media_ids", new StringBody(ids_string));
                reqEntity.addPart("status", new StringBody(text));
                reqEntity.addPart("trim_user", new StringBody("1"));
                request2.setEntity(reqEntity);

                request2.setParams(params);
                request2.addHeader("Authorization", authorization_header_string);
                httpexecutor.preProcess(request2, httpproc, context);
                HttpResponse response2 = httpexecutor.execute(request2, conn, context);
                response2.setParams(params);
                httpexecutor.postProcess(response2, httpproc, context);
                String responseBody = EntityUtils.toString(response2.getEntity());
                System.out.println("response=" + responseBody);
                // error checking here. Otherwise, status should be updated.
                jsonresponse = new JSONObject(responseBody);
                conn.close();
            } catch (HttpException he) {
                System.out.println(he.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus HttpException message=" + he.getMessage());
            } catch (NoSuchAlgorithmException nsae) {
                System.out.println(nsae.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message",
                        "updateStatus NoSuchAlgorithmException message=" + nsae.getMessage());
            } catch (KeyManagementException kme) {
                System.out.println(kme.getMessage());
                jsonresponse.put("response_status", "error");
                jsonresponse.put("message", "updateStatus KeyManagementException message=" + kme.getMessage());
            } finally {
                conn.close();
            }
        } catch (JSONException jsone) {
            jsone.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    } catch (Exception e) {

    }
    return true;
}

From source file:com.mirth.connect.connectors.mllp.MllpMessageDispatcher.java

protected void createSocket(Socket socket, InetSocketAddress inetAddress) throws IOException {
    socket.connect(inetAddress, connector.getReconnectMillisecs());
}

From source file:com.owncloud.android.oc_framework.network.AdvancedSslSocketFactory.java

/**
  * Attempts to get a new socket connection to the given host within the
  * given time limit.//from ww w .j  av  a  2 s. 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
  */
public Socket createSocket(final String host, final int port, final InetAddress localAddress,
        final int localPort, final HttpConnectionParams params)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    Log.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.d(TAG, " ... with connection timeout " + timeout + " and socket timeout " + params.getSoTimeout());
    Socket socket = socketfactory.createSocket();
    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:au.edu.monash.merc.capture.util.httpclient.ssl.SocketFactoryWrapper.java

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException, UnknownHostException, ConnectTimeoutException {
    // Based on code from EasySSLProtocolSocketFactory.java
    Socket rval;
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }/*from w  w w.ja v  a2s  .  com*/
    int timeout = params.getConnectionTimeout();
    if (timeout == 0) {
        rval = socketFactory.createSocket(host, port, localAddress, localPort);
    } else {
        rval = socketFactory.createSocket();
        SocketAddress localaddr = new InetSocketAddress(localAddress, localPort);
        SocketAddress remoteaddr = new InetSocketAddress(host, port);
        rval.bind(localaddr);
        rval.connect(remoteaddr, timeout);
    }
    return rval;
}