Example usage for javax.net SocketFactory createSocket

List of usage examples for javax.net SocketFactory createSocket

Introduction

In this page you can find the example usage for javax.net SocketFactory createSocket.

Prototype

public abstract Socket createSocket(InetAddress host, int port) throws IOException;

Source Link

Document

Creates a socket and connects it to the specified port number at the specified address.

Usage

From source file:com.cloupia.feature.nimble.http.MySSLSocketFactory.java

@Override
public Socket createSocket(String host, int port, InetAddress localAddress, int localPort,
        HttpConnectionParams arg4) throws IOException, UnknownHostException, ConnectTimeoutException {
    TrustManager[] trustAllCerts = getTrustManager();

    try {/*from   ww  w. j  ava2  s.  c o m*/

        SSLContext sc = SSLContext.getInstance("SSL");

        sc.init(null, trustAllCerts, new java.security.SecureRandom());

        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        SocketFactory socketFactory = HttpsURLConnection.getDefaultSSLSocketFactory();

        return socketFactory.createSocket(host, port);

    }

    catch (Exception ex) {

        throw new UnknownHostException("Problems to connect " + host + ex.toString());

    }

}

From source file:com.jkoolcloud.jesl.net.socket.SocketClient.java

/**
 * {@inheritDoc}//from  ww  w  . j a  v  a  2s  .c o  m
 */
@Override
public synchronized void connect() throws IOException {
    if (isConnected())
        return;
    if (secure) {
        SocketFactory socketFactory = SSLSocketFactory.getDefault();
        socket = socketFactory.createSocket(host, port);
    } else {
        socket = new Socket(host, port);
    }
    out = new DataOutputStream(socket.getOutputStream());
    in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
}

From source file:org.apache.camel.component.smpp.SmppConnectionFactory.java

public Connection createConnection(String host, int port) throws IOException {
    try {/* w  w  w .  j  av  a 2s.c  om*/
        Socket socket;
        SocketFactory socketFactory;
        socketFactory = config.getUsingSSL() ? SSLSocketFactory.getDefault() : SocketFactory.getDefault();
        if (config.getHttpProxyHost() != null) {
            socket = socketFactory.createSocket(config.getHttpProxyHost(), config.getHttpProxyPort());
            connectProxy(host, port, socket);
        } else {
            socket = socketFactory.createSocket(host, port);
        }
        return new SocketConnection(socket);

    } catch (Exception e) {
        throw new IOException(e.getMessage());
    }
}

From source file:bigbird.benchmark.BenchmarkWorker.java

public void run() {

    HttpResponse response = null;//from w w  w. java  2  s  . c o m
    DefaultHttpClientConnection conn = new DefaultHttpClientConnection();

    String hostname = targetHost.getHostName();
    int port = targetHost.getPort();
    if (port == -1) {
        port = 80;
    }

    // Populate the execution context
    this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
    this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost);
    //        this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request);

    stats.start();
    for (int i = 0; i < count; i++) {

        try {
            HttpRequest req = requestGenerator.generateRequest(count);

            if (!conn.isOpen()) {
                Socket socket = null;
                if ("https".equals(targetHost.getSchemeName())) {
                    SocketFactory socketFactory = SSLSocketFactory.getDefault();
                    socket = socketFactory.createSocket(hostname, port);
                } else {
                    socket = new Socket(hostname, port);
                }
                conn.bind(socket, params);
            }

            try {
                // Prepare request
                this.httpexecutor.preProcess(req, this.httpProcessor, this.context);
                // Execute request and get a response
                response = this.httpexecutor.execute(req, conn, this.context);
                // Finalize response
                this.httpexecutor.postProcess(response, this.httpProcessor, this.context);

            } catch (HttpException e) {
                stats.incWriteErrors();
                if (this.verbosity >= 2) {
                    System.err.println("Failed HTTP request : " + e.getMessage());
                }
                continue;
            }

            verboseOutput(req, response);

            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                stats.incSuccessCount();
            } else {
                stats.incFailureCount();
                continue;
            }

            HttpEntity entity = response.getEntity();
            String charset = EntityUtils.getContentCharSet(entity);
            if (charset == null) {
                charset = HTTP.DEFAULT_CONTENT_CHARSET;
            }
            long contentlen = 0;
            if (entity != null) {
                InputStream instream = entity.getContent();
                int l = 0;
                while ((l = instream.read(this.buffer)) != -1) {
                    stats.incTotalBytesRecv(l);
                    contentlen += l;
                    if (this.verbosity >= 4) {
                        String s = new String(this.buffer, 0, l, charset);
                        System.out.print(s);
                    }
                }
                instream.close();
            }

            if (this.verbosity >= 4) {
                System.out.println();
                System.out.println();
            }

            if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) {
                conn.close();
            }
            stats.setContentLength(contentlen);

        } catch (IOException ex) {
            ex.printStackTrace();
            stats.incFailureCount();
            if (this.verbosity >= 2) {
                System.err.println("I/O error: " + ex.getMessage());
            }
        }

    }
    stats.finish();

    if (response != null) {
        Header header = response.getFirstHeader("Server");
        if (header != null) {
            stats.setServerName(header.getValue());
        }
    }

    try {
        conn.close();
    } catch (IOException ex) {
        ex.printStackTrace();
        stats.incFailureCount();
        if (this.verbosity >= 2) {
            System.err.println("I/O error: " + ex.getMessage());
        }
    }
}

From source file:pl.otros.logview.gui.actions.ConnectToSocketHubAppenderAction.java

protected Socket tryToConnectToSocket(DataConfiguration configuration, String hostAndPortString,
        SocketFactory socketFactory) throws IOException {
    List<Object> list1 = configuration.getList(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES);
    String[] hostPort = hostAndPortString.split(":");
    host = hostPort[0];//  www.  j a v a 2s .  com
    if (hostPort.length > 1) {
        port = Integer.parseInt(hostPort[1]);
    } else {
        port = 4560;
    }

    Socket socket = socketFactory.createSocket(host, port);
    if (list1.contains(hostAndPortString)) {
        list1.remove(hostAndPortString);
    }
    list1.add(0, hostAndPortString);
    if (list1.size() > 30) {
        list1.remove(list1.size() - 1);
    }
    configuration.setProperty(ConfKeys.SOCKET_HUB_APPENDER_ADDRESSES, list1);
    return socket;
}

From source file:client.ui.Container.java

private JSONObject getCert(SocketFactory factory, URL url) {
    JSONObject json = new JSONObject();
    json.put("host", url.getHost());
    json.put("port", url.getPort());

    try {/*  w w  w. ja va  2 s .  c om*/
        log("Get Certs: " + url.getHost() + ":" + url.getPort());

        SSLSocket socket = (SSLSocket) factory.createSocket(url.getHost(), url.getPort());
        socket.startHandshake();

        Certificate[] certs = socket.getSession().getPeerCertificates();
        String result = "";

        for (Certificate cert : certs) {

            if (cert instanceof X509Certificate) {
                try {
                    ((X509Certificate) cert).checkValidity();
                    result += "OK ";

                } catch (CertificateExpiredException cee) {
                    result += "Expired ";
                } catch (CertificateNotYetValidException ex) {
                    result += "NotYetValid ";
                }
            }
        }

        log("Result: " + result.trim());
        json.put("result", result.trim());

    } catch (SSLException se) {
        log("Error: SSLException (" + se.getMessage() + ")");
        json.put("result", "SSLException: " + se.getMessage());
    } catch (ConnectException ce) {
        log("Error: ConnectException (" + ce.getMessage() + ")");
        json.put("result", "ConnectException: " + ce.getMessage());
    } catch (IOException ioe) {
        log("Error: IOException (" + ioe.getMessage() + ")");
        json.put("result", "IOException: " + ioe.getMessage());
    }

    return json;
}

From source file:net.hiroq.rxwsc.RxWebSocketClient.java

/**
 * Connect to WebSocketServer with additional Header.
 * When unsubscribe is called, the observable will disconnect automatically.
 * <p>//ww w .  j  av  a2s. c  o m
 * Caution: This method run on same thread of caller. So if you want to run on NOT UI THREAD,
 * you have to use subscribeOn to specify thread model.
 *
 * @param uri
 * @param extraHeaders
 * @return
 */
public Observable<Event> connect(Uri uri, List<Pair<String, String>> extraHeaders) {
    this.disconnect(false);

    this.mUri = uri;
    this.mExtraHeaders = extraHeaders;
    this.mParser = new HybiParser(this);

    this.mHandlerThread = new HandlerThread(getClass().getName());
    this.mHandlerThread.start();
    this.mHandler = new Handler(mHandlerThread.getLooper());

    return Observable.create(new Observable.OnSubscribe<Event>() {
        @Override
        public void call(Subscriber<? super Event> subscriber) {
            try {
                mSubscriber = subscriber;
                String secret = createSecret();
                String scheme = mUri.getScheme();

                // uri have invalid scheme throw MalformedURLException
                if (scheme == null || !(scheme.equals("ws") || scheme.equals("wss"))) {
                    new MalformedURLException("Url scheme has to be specified as \"ws\" or \"wss\".");
                }

                int port = (mUri.getPort() != -1) ? mUri.getPort() : (scheme.equals("wss") ? 443 : 80);
                String path = TextUtils.isEmpty(mUri.getPath()) ? "/" : mUri.getPath();
                if (!TextUtils.isEmpty(mUri.getQuery())) {
                    path += "?" + mUri.getQuery();
                }

                String originScheme = scheme.equals("wss") ? "https" : "http";
                Uri origin = Uri.parse(originScheme + "://" + mUri.getHost());

                SocketFactory factory = scheme.equals("wss") ? getSSLSocketFactory()
                        : SocketFactory.getDefault();
                mSocket = factory.createSocket(mUri.getHost(), port);

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mUri.getHost() + "\r\n");
                out.print("Origin: " + origin.toString() + "\r\n");
                out.print("Sec-WebSocket-Key: " + secret + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (Pair<String, String> pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.first, pair.second));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                        mSocket.getInputStream());

                // Read HTTP response status line.
                StatusLine statusLine = parseStatusLine(readLine(stream));
                if (statusLine == null) {
                    throw new ConnectException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new ProtocolException(
                            "Server sent invalid response code " + statusLine.getStatusCode()
                                    + ". WebSocket server must return " + HttpStatus.SC_SWITCHING_PROTOCOLS);
                }

                // Read HTTP response headers.
                String line;
                boolean validated = false;

                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        String expected = createSecretValidation(secret);
                        String actual = header.getValue().trim();

                        if (!expected.equals(actual)) {
                            throw new ProtocolException("Bad Sec-WebSocket-Accept header value.");
                        }

                        validated = true;
                    }
                }

                if (!validated) {
                    throw new ProtocolException("No Sec-WebSocket-Accept header.");
                }

                mIsConnected = true;
                emitterOnNext(new Event(EventType.CONNECT));

                // Now decode websocket frames.
                mParser.start(stream);
            } catch (Exception e) {
                emitterOnError(e);
            }
        }
    }).doOnUnsubscribe(new Action0() {
        @Override
        public void call() {
            RxWebSocketClient.this.disconnect(false);
        }
    });
}

From source file:com.leanplum.internal.WebSocketClient.java

public void connect() {
    if (mThread != null && mThread.isAlive()) {
        return;//from   ww w  .j a  va2s .  c  o m
    }

    mThread = new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                int port = (mURI.getPort() != -1) ? mURI.getPort()
                        : (mURI.getScheme().equals("wss") ? 443 : 80);

                String path = TextUtils.isEmpty(mURI.getPath()) ? "/" : mURI.getPath();
                if (!TextUtils.isEmpty(mURI.getQuery())) {
                    path += "?" + mURI.getQuery();
                }

                String originScheme = mURI.getScheme().equals("wss") ? "https" : "http";
                URI origin = null;
                try {
                    origin = new URI(originScheme, "//" + mURI.getHost(), null);
                } catch (URISyntaxException e) {
                    Util.handleException(e);
                }

                SocketFactory factory;
                try {
                    factory = mURI.getScheme().equals("wss") ? getSSLSocketFactory()
                            : SocketFactory.getDefault();
                } catch (GeneralSecurityException e) {
                    Util.handleException(e);
                    return;
                }
                try {
                    mSocket = factory.createSocket(mURI.getHost(), port);
                } catch (IOException e) {
                    Util.handleException(e);
                }

                PrintWriter out = new PrintWriter(mSocket.getOutputStream());
                out.print("GET " + path + " HTTP/1.1\r\n");
                out.print("Upgrade: websocket\r\n");
                out.print("Connection: Upgrade\r\n");
                out.print("Host: " + mURI.getHost() + "\r\n");
                out.print("Origin: " + (origin != null ? origin.toString() : "unknown") + "\r\n");
                out.print("Sec-WebSocket-Key: " + createSecret() + "\r\n");
                out.print("Sec-WebSocket-Version: 13\r\n");
                if (mExtraHeaders != null) {
                    for (NameValuePair pair : mExtraHeaders) {
                        out.print(String.format("%s: %s\r\n", pair.getName(), pair.getValue()));
                    }
                }
                out.print("\r\n");
                out.flush();

                HybiParser.HappyDataInputStream stream = new HybiParser.HappyDataInputStream(
                        mSocket.getInputStream());

                // Read HTTP response status line.

                StatusLine statusLine = parseStatusLine(readLine(stream));

                if (statusLine == null) {
                    throw new HttpException("Received no reply from server.");
                } else if (statusLine.getStatusCode() != HttpStatus.SC_SWITCHING_PROTOCOLS) {
                    throw new HttpResponseException(statusLine.getStatusCode(), statusLine.getReasonPhrase());
                }

                // Read HTTP response headers.
                String line;
                while (!TextUtils.isEmpty(line = readLine(stream))) {
                    Header header = parseHeader(line);
                    if (header.getName().equals("Sec-WebSocket-Accept")) {
                        // FIXME: Verify the response...
                    }
                }

                mListener.onConnect();

                // Now decode websocket frames.
                mParser.start(stream);

            } catch (EOFException ex) {
                Log.d("WebSocket EOF!", ex);
                mListener.onDisconnect(0, "EOF");

            } catch (SSLException ex) {
                // Connection reset by peer
                Log.d("Websocket SSL error!", ex);
                mListener.onDisconnect(0, "SSL");

            } catch (Exception e) {
                mListener.onError(e);
            }
        }
    });
    mThread.start();
}

From source file:net.jotel.ws.client.WebSocketClient.java

private Socket createSocket() throws IOException {
    Socket s;/*from www.j  a v  a 2  s .  co  m*/
    if (secure) {
        SocketFactory factory = SSLSocketFactory.getDefault();
        s = factory.createSocket(host, port);
    } else {
        s = new Socket(host, port);
    }
    s.setKeepAlive(true);
    s.setSoTimeout(100000);

    return s;
}