List of usage examples for javax.net SocketFactory getDefault
public static SocketFactory getDefault()
From source file:com.appunite.websocket.WebSocket.java
/** * This method will be alive until error occur or interrupt was executed. * This method always throws some exception. (not thread safe) * //from w w w .j a v a2 s. c om * @param uri * uri of websocket * @throws UnknownHostException * when could not connect to selected host * @throws IOException * thrown when I/O exception occur * @throws WrongWebsocketResponse * thrown when wrong web socket response received * @throws InterruptedException * thrown when interrupt method was invoked */ public void connect(Uri uri) throws IOException, WrongWebsocketResponse, InterruptedException { checkNotNull(uri, "Uri cannot be null"); try { synchronized (mLockObj) { checkState(State.DISCONNECTED.equals(mState), "connect could be called only if disconnected"); SocketFactory factory; if (isSsl(uri)) { factory = SSLSocketFactory.getDefault(); } else { factory = SocketFactory.getDefault(); } mSocket = factory.createSocket(); mState = State.CONNECTING; mLockObj.notifyAll(); } mSocket.connect(new InetSocketAddress(uri.getHost(), getPort(uri))); mInputStream = new WebSocketReader(mSocket.getInputStream()); mOutputStream = new WebSocketWriter(mSocket.getOutputStream()); String secret = generateHandshakeSecret(); writeHeaders(uri, secret); readHandshakeHeaders(secret); } catch (IOException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw e; } } } finally { synchronized (mLockObj) { mState = State.DISCONNECTED; mLockObj.notifyAll(); } } try { synchronized (mLockObj) { mState = State.CONNECTED; mLockObj.notifyAll(); } mListener.onConnected(); //noinspection InfiniteLoopStatement for (;;) { doRead(); } } catch (NotConnectedException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw new RuntimeException(); } } } catch (IOException e) { synchronized (mLockObj) { if (State.DISCONNECTING.equals(mState)) { throw new InterruptedException(); } else { throw e; } } } finally { synchronized (mLockObj) { while (mWriting != 0) { mLockObj.wait(); } mState = State.DISCONNECTED; mLockObj.notifyAll(); } } }
From source file:com.leetchi.api.client.ssl.SSLConnectionSocketFactory.java
public Socket createSocket(final HttpContext context) throws IOException { return SocketFactory.getDefault().createSocket(); }
From source file:it.jnrpe.client.JNRPEClient.java
/** * Inovoke a command installed in JNRPE. * //from ww w.ja v a 2 s .c o m * @param sCommandName * The name of the command to be invoked * @param arguments * The arguments to pass to the command (will substitute the * $ARGSx$ parameters) * @return The value returned by the server * @throws JNRPEClientException * Thrown on any communication error. */ public final ReturnValue sendCommand(final String sCommandName, final String... arguments) throws JNRPEClientException { SocketFactory socketFactory; Socket s = null; try { if (!useSSL) { socketFactory = SocketFactory.getDefault(); } else { SSLContext sslContext = SSLContext.getInstance("TLSv1.2"); sslContext.init(null, new TrustManager[] { getTrustManager() }, new SecureRandom()); socketFactory = sslContext.getSocketFactory(); } s = socketFactory.createSocket(); if (weakCipherSuitesEnabled) { SSLSocket ssl = (SSLSocket) s; ssl.setEnabledCipherSuites(ssl.getSupportedCipherSuites()); } s.setSoTimeout((int) TimeUnit.SECOND.convert(communicationTimeout)); s.connect(new InetSocketAddress(serverIPorURL, serverPort)); JNRPERequest req = new JNRPERequest(sCommandName, arguments); s.getOutputStream().write(req.toByteArray()); InputStream in = s.getInputStream(); JNRPEResponse res = new JNRPEResponse(in); return new ReturnValue(Status.fromIntValue(res.getResultCode()), res.getMessage()); } catch (RuntimeException re) { throw re; } catch (Exception e) { throw new JNRPEClientException(e); } finally { if (s != null) { try { s.close(); } catch (IOException e) { // Ignore } } } }
From source file:de.vanita5.twittnuker.util.net.ssl.HostResolvedSSLConnectionSocketFactory.java
@Override public Socket createSocket(final HttpContext context) throws IOException { return SocketFactory.getDefault().createSocket(); }
From source file:com.zimbra.common.net.SocketFactories.java
/** * Returns the default SocketFactory using SOCKS if configured. * * @return the default SocketFactoryh//from w w w . ja v a2 s. c om */ public static SocketFactory defaultSocketFactory() { return config.isSocksEnabled() ? proxySelectorSocketFactory() : SocketFactory.getDefault(); }
From source file:com.irccloud.android.HTTPFetcher.java
public void connect() { if (mThread != null && mThread.isAlive()) { return;/*w ww . j a v a 2s.c o m*/ } mThread = new Thread(new Runnable() { @Override public void run() { try { if (isCancelled) return; Crashlytics.log(Log.INFO, TAG, "Requesting: " + mURI); int port = (mURI.getPort() != -1) ? mURI.getPort() : (mURI.getProtocol().equals("https") ? 443 : 80); SocketFactory factory = mURI.getProtocol().equals("https") ? getSSLSocketFactory() : SocketFactory.getDefault(); if (mProxyHost != null && mProxyHost.length() > 0 && mProxyPort > 0) { Crashlytics.log(Log.INFO, TAG, "Connecting to proxy: " + mProxyHost + " port: " + mProxyPort); mSocket = SocketFactory.getDefault().createSocket(mProxyHost, mProxyPort); mThread = new Thread(new Runnable() { @SuppressLint("NewApi") public void run() { http_thread(); } }); mThread.setName("http-stream-thread"); mThread.start(); } else { InetAddress[] addresses = InetAddress.getAllByName(mURI.getHost()); mAddressCount = addresses.length; for (InetAddress address : addresses) { if (mSocket == null && !isCancelled) { if (mSocketThreads.size() >= MAX_THREADS) { Crashlytics.log(Log.INFO, TAG, "Waiting for other HTTP requests to complete before continuing"); while (mSocketThreads.size() >= MAX_THREADS) { Thread.sleep(1000); } } Thread t = new Thread( new ConnectRunnable(factory, new InetSocketAddress(address, port))); mSocketThreads.add(t); mCurrentSocketThreads.add(t); mAttempts++; t.start(); Thread.sleep(300); } else { break; } } } } catch (Exception ex) { ex.printStackTrace(); } } }); mThread.start(); }
From source file:net.hiroq.rxwsc.RxWebSocketClient.java
/** * Connect to WebSocketServer with additional Header. * When unsubscribe is called, the observable will disconnect automatically. * <p>/*from w w w .jav a2 s. 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.zimbra.cs.mailclient.MailConnection.java
private SocketFactory getSocketFactory() { SocketFactory sf = config.getSocketFactory(); return sf != null ? sf : SocketFactory.getDefault(); }
From source file:com.github.hrpc.rpc.ProtobufRpcEngine.java
static Client getClient(Option conf) { return CLIENTS.getClient(conf, SocketFactory.getDefault(), RpcResponseWrapper.class); }
From source file:cache.reverseproxy.CacheableServicesReverseProxy.java
public static Socket createInsecureSocket(String host, int port) throws IOException { Socket newSocket = (Socket) SocketFactory.getDefault().createSocket(host, port); return newSocket; }