SSLSocketBuilder { public SSLSocket build() throws IOException { try { SSLContext sslContext = SSLContext.getInstance(SSL_PROTOCOL); sslContext.init(null, null, new SecureRandom()); javax.net.ssl.SSLSocketFactory socketFactory = sslContext.getSocketFactory(); Socket socket = new Socket(); try { socket.connect(new InetSocketAddress(host, port), connectionTimeoutMilli); socket.setTcpNoDelay(true); socket.setSoTimeout(readTimeoutMilli); return (SSLSocket) socketFactory.createSocket(socket, host, port, true); } catch (Throwable e) { socket.close(); throw e; } } catch (NoSuchAlgorithmException e) { throw new IllegalStateException("Failed to get SSLContext", e); } catch (KeyManagementException e) { throw new IllegalStateException("Failed to init SSLContext", e); } } SSLSocketBuilder(String host, Integer port, int connectionTimeoutMilli, int readTimeoutMilli); SSLSocket build(); @Override String toString();  }
@Test void testWithServer() throws IOException, InterruptedException, ExecutionException, TimeoutException { final AtomicInteger readLen = new AtomicInteger(); final byte[] buf = new byte[256]; ExecutorService executorService = Executors.newSingleThreadExecutor(); Future<Void> future = executorService.submit(new Callable<Void>() { @Override public Void call() throws Exception { Socket clientSocket = serverSocket.accept(); readLen.set(clientSocket.getInputStream().read(buf)); return null; } }); SSLSocket sslSocket = new SSLSocketBuilder("localhost", serverSocket.getLocalPort(), 5000, 5000).build(); try { OutputStream outputStream = sslSocket.getOutputStream(); outputStream.write("hello".getBytes("ASCII")); outputStream.flush(); } finally { sslSocket.close(); } future.get(10, TimeUnit.SECONDS); executorService.shutdown(); executorService.awaitTermination(10, TimeUnit.SECONDS); assertEquals(new String(buf, 0, readLen.get(), "ASCII"), "hello"); }