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:ucf.cap4104.group17.factorcrap.Welcome.java

/**
 * http://stackoverflow.com/a/27312494//from  w  w  w .j  av  a  2s  . c o m
 * Author: Levit
 * licensed under cc by-sa 3.0 with attribution required
 * Checks if the user actually has internet, and not just WiFi
 */
private void checkIfHasInternet() {
    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                int timeoutMs = 1500;
                Socket sock = new Socket();
                SocketAddress socketAddress = new InetSocketAddress("8.8.8.8", 53);
                sock.connect(socketAddress, timeoutMs);
                sock.close();
                setAccordingToInternet(true);
            } catch (IOException ignored) {
                setAccordingToInternet(false);
            }
        }
    }).start();
}

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

public Bitmap getDMPicture(String picUrl, Twitter twitter) {

    try {/* w  w  w .  jav  a 2  s  .c o m*/
        AccessToken token = twitter.getOAuthAccessToken();
        String oauth_token = token.getToken();
        String oauth_token_secret = token.getTokenSecret();

        // generate authorization header
        String get_or_post = "GET";
        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";

        String twitter_endpoint = picUrl;
        String twitter_endpoint_host = picUrl.substring(0, picUrl.indexOf("1.1")).replace("https://", "")
                .replace("/", "");
        String twitter_endpoint_path = picUrl.replace("ton.twitter.com", "").replace("https://", "");
        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));

        Log.v("talon_dm_image", "endpoint_host: " + twitter_endpoint_host);
        Log.v("talon_dm_image", "endpoint_path: " + twitter_endpoint_path);

        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);

        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("GET",
                twitter_endpoint_path);
        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);

        StatusLine statusLine = response2.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200 || statusCode == 302) {
            HttpEntity entity = response2.getEntity();
            byte[] bytes = EntityUtils.toByteArray(entity);

            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            Log.v("talon_dm_image", statusCode + "");
        }

        conn.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:org.hyperic.hq.plugin.netservices.NetServicesCollector.java

public SocketWrapper getSocketWrapper(boolean acceptUnverifiedCertificatesOverride) throws IOException {
    if (isSSL()) {
        // Sometimes we may want to override what's set in the keystore config...mostly for init purposes...
        boolean accept = acceptUnverifiedCertificatesOverride ? true : keystoreConfig.isAcceptUnverifiedCert();
        SSLProvider sslProvider = new DefaultSSLProviderImpl(keystoreConfig, accept);
        SSLSocketFactory factory = sslProvider.getSSLSocketFactory();
        Socket socket = factory.createSocket();

        socket.connect(getSocketAddress(), getTimeoutMillis());
        socket.setSoTimeout(getTimeoutMillis());
        ((SSLSocket) socket).startHandshake();

        return new SocketWrapper(socket);
    } else {/*from   w  w  w .  j av a  2 s  .  c om*/
        Socket socket = new Socket();
        connect(socket);
        return new SocketWrapper(socket);
    }
}

From source file:io.aino.agents.core.AgentIntegrationTest.java

private boolean isReachable(String host, int port, int timeout) throws IOException {
    SocketAddress proxyAddress = new InetSocketAddress(host, port);
    Socket socket = new Socket();
    try {//from  w  ww.j a  va 2  s.c o m
        socket.connect(proxyAddress, timeout);
        //System.out.println("Connected to: " + host + ":" + port);
        return socket.isConnected();
    } catch (IOException e) {
        System.out.println("Could not connect to: " + host + ":" + port);
        return false;
    } finally {
        if (socket.isConnected()) {
            //System.out.println("Closing connection to: " + host + ":" + port);
            socket.close();
            //System.out.println("Disconnected: " + host + ":" + port);
        }
    }
}

From source file:com.supernovapps.audio.jstreamsourcer.ShoutcastV1.java

public boolean start(Socket sock) {
    try {//from w w  w  .ja v a  2 s. c o m
        this.sock = sock;
        sock.connect(new InetSocketAddress(host, port), 5000);
        sock.setSendBufferSize(64 * 1024);
        out = sock.getOutputStream();

        PrintWriter output = writeAuthentication();

        InputStreamReader isr = new InputStreamReader(sock.getInputStream());
        BufferedReader in = new BufferedReader(isr);
        String line = in.readLine();
        if (line == null || !line.contains("OK")) {
            if (listener != null) {
                listener.onError("Connection / Authentification error");
            }

            return false;
        }

        while (line != null && line.length() > 0) {
            line = in.readLine();
        }

        writeHeaders(output);
    } catch (Exception e) {
        e.printStackTrace();

        try {
            if (sock != null)
                sock.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }

        if (listener != null) {
            listener.onError("Connection / Authentification error");
        }

        return false;
    }
    started = true;

    if (listener != null) {
        listener.onConnected();
    }

    return true;
}

From source file:org.candlepin.client.AbstractSLLProtocolSocketFactory.java

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");
    }/*from www  .  ja  va  2 s. co  m*/
    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:open.hyperion.nimblestorage.connection.NonValidatingSocketFactory.java

@Override
public Socket createSocket(String s, int i, InetAddress inetAddress, int i1,
        HttpConnectionParams httpConnectionParams)
        throws IOException, UnknownHostException, ConnectTimeoutException {
    int timeout = httpConnectionParams.getConnectionTimeout();
    Socket socket = _sslContext.getSocketFactory().createSocket();
    SocketAddress localaddr = new InetSocketAddress(inetAddress, i1);
    SocketAddress remoteaddr = new InetSocketAddress(s, i);
    socket.bind(localaddr);/*from  w  w  w  .j a va2 s. c  o m*/
    socket.connect(remoteaddr, timeout);
    return socket;
}

From source file:com.sun.faban.driver.transport.hc3.AboveTimedSSLSocketFactory.java

public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams params) throws IOException {
    if (params == null) {
        throw new IllegalArgumentException("Parameters may not be null");
    }/* w w  w.ja va2s  . co m*/
    int timeout = params.getConnectionTimeout();
    if (timeout <= 0) {
        return createSocket(host, port, localAddress, localPort);
    } else {
        Socket socket = new TimedSocketWrapper(sslFactory.createSocket());
        InetSocketAddress endpoint = new InetSocketAddress(host, port);
        socket.bind(new InetSocketAddress(localAddress, localPort));
        socket.connect(endpoint, timeout);
        return socket;
    }
}

From source file:org.apache.axis2.java.security.SSLProtocolSocketFactory.java

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");
    }//from ww w  . ja v  a2s.c  o m
    int timeout = params.getConnectionTimeout();
    SocketFactory socketfactory = ctx.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.cazoodle.crawl.DummySSLProtocolSocketFactory.java

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");
    }/*  w ww  .j a  v a  2s. c  o m*/
    int timeout = params.getConnectionTimeout();
    if (timeout > 0) {
        Socket socket = getSSLContext().getSocketFactory().createSocket();
        socket.bind(new InetSocketAddress(localAddress, localPort));
        socket.setSoTimeout(timeout);
        socket.connect(new InetSocketAddress(getInetAddress(host), port), timeout);
        return socket;
    } else {
        return createSocket(host, port, localAddress, localPort);
    }
}