Java Code Examples for javax.net.ssl.SSLSocket#close()

The following examples show how to use javax.net.ssl.SSLSocket#close() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: EmptyCertificateAuthorities.java    From openjdk-jdk9 with GNU General Public License v2.0 7 votes vote down vote up
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf = getSSLServerSF();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    // require client authentication.
    sslServerSocket.setNeedClientAuth(true);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write('A');
    sslOS.flush();

    sslSocket.close();
}
 
Example 2
Source File: GenericBlockCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 6 votes vote down vote up
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    sslIS.read();
    sslOS.write('A');
    sslOS.flush();

    sslSocket.close();
}
 
Example 3
Source File: Server.java    From jdk9-jigsaw with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
public static void main(String[] args) throws IOException{
	
	System.setProperty("javax.net.ssl.keyStore", "C:/Users/Martin/sample.pfx");
	System.setProperty("javax.net.ssl.keyStorePassword", "sample");
	
	SSLServerSocketFactory ssf = (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    ServerSocket ss = ssf.createServerSocket(4444);
    while (true) {
      SSLSocket s = (SSLSocket) ss.accept();
      SSLParameters params = s.getSSLParameters();
      
      s.setSSLParameters(params);
      
      BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
      String line = null;
      PrintStream out = new PrintStream(s.getOutputStream());
      while (((line = in.readLine()) != null)) {
        System.out.println(line);
	    out.println("Hi, client");
      }
      in.close();
      out.close();
      s.close();
    }
    
}
 
Example 4
Source File: Client.java    From jdk9-jigsaw with Creative Commons Zero v1.0 Universal 6 votes vote down vote up
public static void main(String[] args) throws InterruptedException {
	
	try {
		System.setProperty("javax.net.ssl.trustStore", "C:/Users/Martin/sample.pfx");
		System.setProperty("javax.net.ssl.trustStorePassword", "sample");
		
		SSLSocketFactory ssf = (SSLSocketFactory) SSLSocketFactory.getDefault();
		SSLSocket s = (SSLSocket) ssf.createSocket("127.0.0.1", 4444);
		SSLParameters params = s.getSSLParameters();
		s.setSSLParameters(params);
		
		PrintWriter out = new PrintWriter(s.getOutputStream(), true);
		out.println("Hi, server.");
		BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
		String x = in.readLine();
		System.out.println(x);
		System.out.println("Used protocol: " + s.getApplicationProtocol());
		
		out.close();
		in.close();
		s.close();
	} catch (Exception ex) {
		ex.printStackTrace();
	}
	
}
 
Example 5
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * javax.net.ssl.SSLSocket#getUseClientMode()
 * javax.net.ssl.SSLSocket#setUseClientMode(boolean mode)
 */
public void j2objcNotImplemented_test_UseClientMode() throws IOException {
    SSLSocket ssl = getSSLSocket();
    assertTrue(ssl.getUseClientMode());
    ssl.setUseClientMode(false);
    assertFalse(ssl.getUseClientMode());
    ssl.close();

    ssl = getSSLSocket("localhost", startServer("UseClientMode"));
    try {
        ssl.startHandshake();
    } catch (IOException ioe) {
        //fail(ioe + " was thrown for method startHandshake()");
    }
    try {
        ssl.setUseClientMode(false);
        fail();
    } catch (IllegalArgumentException expected) {
    }
    ssl.close();
}
 
Example 6
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * javax.net.ssl.SSLSocket#setEnableSessionCreation(boolean flag)
 * javax.net.ssl.SSLSocket#getEnableSessionCreation()
 */
public void j2objcNotImplemented_test_EnableSessionCreation() throws IOException {
    SSLSocket ssl = getSSLSocket();
    assertTrue(ssl.getEnableSessionCreation());
    ssl.setEnableSessionCreation(false);
    assertFalse(ssl.getEnableSessionCreation());
    ssl.setEnableSessionCreation(true);
    assertTrue(ssl.getEnableSessionCreation());
    ssl.close();
}
 
Example 7
Source File: HandshakeCompletedEventTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void run() {
    try {
        SSLSocket clientSocket = (SSLSocket)serverSocket.accept();

        InputStream istream = clientSocket.getInputStream();

        for (int i = 0; i < 256; i++) {
            int j = istream.read();
            assertEquals(i, j);
        }

        istream.close();

        OutputStream ostream = clientSocket.getOutputStream();

        for (int i = 0; i < 256; i++) {
            ostream.write(i);
        }

        ostream.flush();
        ostream.close();

        clientSocket.close();
        serverSocket.close();

    } catch (Exception ex) {
        exception = ex;
    }
}
 
Example 8
Source File: SSLPinGenerator.java    From ssl-pin-generator with MIT License 5 votes vote down vote up
private void fetchAndPrintPinHashs() throws Exception {
	System.out.println("**Run this on a trusted network**\nGenerating SSL pins for: " + hostname);
	SSLContext context = SSLContext.getInstance("TLS");
	PublicKeyExtractingTrustManager tm = new PublicKeyExtractingTrustManager();
	context.init(null, new TrustManager[] { tm }, null);
	SSLSocketFactory factory = context.getSocketFactory();
	SSLSocket socket = (SSLSocket) factory.createSocket(hostname, hostPort);
	socket.setSoTimeout(10000);
	socket.startHandshake();
	socket.close();
}
 
Example 9
Source File: ExportableStreamCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doServerSide() throws Exception {
    SSLServerSocketFactory sslssf =
        (SSLServerSocketFactory) SSLServerSocketFactory.getDefault();
    SSLServerSocket sslServerSocket =
        (SSLServerSocket) sslssf.createServerSocket(serverPort);

    serverPort = sslServerSocket.getLocalPort();

    /*
     * Signal Client, we're ready for his connect.
     */
    serverReady = true;

    SSLSocket sslSocket = (SSLSocket) sslServerSocket.accept();
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    boolean interrupted = false;
    try {
        sslIS.read();
        sslOS.write('A');
        sslOS.flush();
    } catch (IOException ioe) {
        // get the expected exception
        interrupted = true;
    } finally {
        sslSocket.close();
    }

    if (!interrupted) {
        throw new SSLHandshakeException(
            "A weak cipher suite is negotiated, " +
            "TLSv1.1 must not negotiate the exportable cipher suites.");
    }
}
 
Example 10
Source File: ECCurvesconstraints.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLContext context = generateSSLContext(true);
        SSLSocketFactory sslsf = context.getSocketFactory();

        SSLSocket sslSocket =
            (SSLSocket)sslsf.createSocket("localhost", serverPort);

        try {
            sslSocket.setSoTimeout(5000);
            sslSocket.setSoLinger(true, 5);

            InputStream sslIS = sslSocket.getInputStream();
            OutputStream sslOS = sslSocket.getOutputStream();

            sslOS.write('B');
            sslOS.flush();
            sslIS.read();

            throw new Exception("EC curve secp224k1 should be disabled");
        } catch (SSLHandshakeException she) {
            // expected exception: Received fatal alert
            System.out.println("Expected exception: " + she);
        } finally {
            sslSocket.close();
        }
    }
 
Example 11
Source File: SslContextNBrokerServiceTest.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
private boolean verifySslCredentials(BrokerService broker) throws Exception {
   TransportConnector connector = broker.getTransportConnectors().get(0);
   URI brokerUri = connector.getConnectUri();

   SSLContext context = SSLContext.getInstance("TLS");
   CertChainCatcher catcher = new CertChainCatcher();
   context.init(null, new TrustManager[]{catcher}, null);

   SSLSocketFactory factory = context.getSocketFactory();
   LOG.info("Connecting to broker: " + broker.getBrokerName() + " on: " + brokerUri.getHost() + ":" + brokerUri.getPort());
   SSLSocket socket = (SSLSocket) factory.createSocket(brokerUri.getHost(), brokerUri.getPort());
   socket.setSoTimeout(2 * 60 * 1000);
   socket.startHandshake();
   socket.close();

   boolean matches = false;
   if (catcher.serverCerts != null) {
      for (int i = 0; i < catcher.serverCerts.length; i++) {
         X509Certificate cert = catcher.serverCerts[i];
         LOG.info(" " + (i + 1) + " Issuer " + cert.getIssuerDN());
      }
      if (catcher.serverCerts.length > 0) {
         String issuer = catcher.serverCerts[0].getIssuerDN().toString();
         if (issuer.indexOf(broker.getBrokerName()) != -1) {
            matches = true;
         }
      }
   }
   return matches;
}
 
Example 12
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_SSLSocket_sendsNoTlsFallbackScsv_Fallback_Success() throws Exception {
    TestSSLContext context = TestSSLContext.create();

    final SSLSocket client = (SSLSocket)
        context.clientContext.getSocketFactory().createSocket(context.host, context.port);
    final SSLSocket server = (SSLSocket) context.serverSocket.accept();

    // Confirm absence of TLS_FALLBACK_SCSV.
    assertFalse(Arrays.asList(client.getEnabledCipherSuites())
            .contains(StandardNames.CIPHER_SUITE_FALLBACK));

    ExecutorService executor = Executors.newFixedThreadPool(2);
    Future<Void> s = executor.submit(new Callable<Void>() {
            public Void call() throws Exception {
                server.setEnabledProtocols(new String[] { "TLSv1", "SSLv3" });
                server.startHandshake();
                return null;
            }
        });
    Future<Void> c = executor.submit(new Callable<Void>() {
            public Void call() throws Exception {
                client.setEnabledProtocols(new String[] { "SSLv3" });
                client.startHandshake();
                return null;
            }
        });
    executor.shutdown();

    s.get();
    c.get();
    client.close();
    server.close();
    context.close();
}
 
Example 13
Source File: SecurityServiceImpl.java    From gvnix with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Get certificates in the chain of the host server and import them.
 * <p>
 * Tries to get the certificates in the certificates chain of the host
 * server and import them to:
 * <ol>
 * <li>A custom keystore in <code>SRC_MAIN_RESOURCES/gvnix-cacerts</code></li>
 * <li>The JVM cacerts keystore in
 * <code>$JAVA_HOME/jre/lib/security/cacerts</code>. Here we can have a
 * problem if JVM <code>cacerts</code> file is not writable by the user due
 * to file permissions. In this case we throw an exception informing about
 * the error.</li>
 * </ol>
 * </p>
 * <p>
 * With that operation we can try again to get the WSDL.<br/>
 * Also it exports the chain certificates to <code>.cer</code> files in
 * <code>SRC_MAIN_RESOURCES</code>, so the developer can distribute them for
 * its installation in other environments or just in case we reach the
 * problem with the JVM <code>cacerts</code> file permissions.
 * </p>
 * 
 * @see GvNix509TrustManager#saveCertFile(String, X509Certificate,
 *      FileManager, PathResolver)
 * @see <a href=
 *      "http://download.oracle.com/javase/6/docs/technotes/tools/solaris/keytool.html"
 *      >Java SE keytool</a>.
 */
protected Document installCertificates(String loc, String pass)
        throws NoSuchAlgorithmException, KeyStoreException, Exception,
        KeyManagementException, MalformedURLException, IOException,
        UnknownHostException, SocketException, SAXException {

    // Create a SSL context
    SSLContext context = SSLContext.getInstance("TLS");
    TrustManagerFactory tmf = TrustManagerFactory
            .getInstance(TrustManagerFactory.getDefaultAlgorithm());

    // Passphrase of the keystore: "changeit" by default
    char[] passArray = (StringUtils.isNotBlank(pass) ? pass.toCharArray()
            : "changeit".toCharArray());

    // Get the project keystore and copy it from JVM if not exists
    File keystore = getProjectKeystore();

    tmf.init(GvNix509TrustManager.loadKeyStore(keystore, passArray));

    X509TrustManager defaultTrustManager = (X509TrustManager) tmf
            .getTrustManagers()[0];
    GvNix509TrustManager tm = new GvNix509TrustManager(defaultTrustManager);
    context.init(null, new TrustManager[] { tm }, null);
    SSLSocketFactory factory = context.getSocketFactory();

    // Open URL location (default 443 port if not defined)
    URL url = new URL(loc);
    String host = url.getHost();
    int port = url.getPort() == -1 ? 443 : url.getPort();
    SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
    socket.setSoTimeout(10000);

    Document doc = null;
    try {

        socket.startHandshake();
        URLConnection connection = url.openConnection();
        if (connection instanceof HttpsURLConnection) {
            ((HttpsURLConnection) connection).setSSLSocketFactory(factory);
        }

        doc = XmlUtils.getDocumentBuilder().parse(
                connection.getInputStream());

        socket.close();

    }
    catch (SSLException ssle) {

        // Get needed certificates for this host
        getCerts(tm, host, keystore, passArray);
        doc = getWsdl(loc, pass);

    }
    catch (IOException ioe) {

        invalidHostCert(passArray, keystore, tm, host);
    }

    Validate.notNull(doc, "No valid document format");
    return doc;
}
 
Example 14
Source File: StartTlsResponseImpl.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 15
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * javax.net.ssl.SSLSocket#SSLSocket()
 */
public void testConstructor() throws Exception {
    SSLSocket ssl = getSSLSocket();
    assertNotNull(ssl);
    ssl.close();
}
 
Example 16
Source File: ExportableStreamCipher.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
void doClientSide() throws Exception {

        /*
         * Wait for server to get started.
         */
        while (!serverReady) {
            Thread.sleep(50);
        }

        SSLSocketFactory sslsf =
            (SSLSocketFactory) SSLSocketFactory.getDefault();
        SSLSocket sslSocket = (SSLSocket)
            sslsf.createSocket("localhost", serverPort);

        // enable TLSv1.1 only
        sslSocket.setEnabledProtocols(new String[] {"TLSv1.1"});

        // enable a exportable stream cipher
        sslSocket.setEnabledCipherSuites(
            new String[] {"SSL_RSA_EXPORT_WITH_RC4_40_MD5"});

        InputStream sslIS = sslSocket.getInputStream();
        OutputStream sslOS = sslSocket.getOutputStream();

        boolean interrupted = false;
        try {
            sslOS.write('B');
            sslOS.flush();
            sslIS.read();
        } catch (SSLException ssle) {
            // get the expected exception
            interrupted = true;
        } finally {
            sslSocket.close();
        }

        if (!interrupted) {
            throw new SSLHandshakeException(
                "A weak cipher suite is negotiated, " +
                "TLSv1.1 must not negotiate the exportable cipher suites.");
        }
    }
 
Example 17
Source File: StartTlsResponseImpl.java    From jdk8u-dev-jdk with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 18
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void run() {
    try {
        /* J2ObjC not implemented
        KeyManager[] keyManagers = provideKeys ? getKeyManagers(keys) : null;
        TrustManager[] trustManagers = new TrustManager[] { trustManager };

        SSLContext sslContext = SSLContext.getInstance("TLS");
        sslContext.init(keyManagers, trustManagers, null);

        SSLServerSocket serverSocket = (SSLServerSocket)
                sslContext.getServerSocketFactory().createServerSocket();
        */
        ServerSocket serverSocket = new ServerSocket();
        try {
            serverSocket.bind(new InetSocketAddress(0));
            sport = serverSocket.getLocalPort();
            serverReady = true;

            SSLSocket clientSocket = (SSLSocket)serverSocket.accept();

            try {
                InputStream stream = clientSocket.getInputStream();
                try {
                    for (int i = 0; i < 256; i++) {
                        int j = stream.read();
                        if (i != j) {
                            throw new RuntimeException("Error reading socket, expected " + i
                                                       + ", got " + j);
                        }
                    }
                } finally {
                    stream.close();
                }
            } finally {
                clientSocket.close();
            }
        } finally {
            serverSocket.close();
        }
    } catch (Exception ex) {
        exception = ex;
    }
}
 
Example 19
Source File: StartTlsResponseImpl.java    From hottub with GNU General Public License v2.0 4 votes vote down vote up
private SSLSocket startHandshake(SSLSocketFactory factory)
    throws IOException {

    if (ldapConnection == null) {
        throw new IllegalStateException("LDAP connection has not been set."
            + " TLS requires an existing LDAP connection.");
    }

    if (factory != currentFactory) {
        // Create SSL socket layered over the existing connection
        sslSocket = (SSLSocket) factory.createSocket(ldapConnection.sock,
            ldapConnection.host, ldapConnection.port, false);
        currentFactory = factory;

        if (debug) {
            System.out.println("StartTLS: Created socket : " + sslSocket);
        }
    }

    if (suites != null) {
        sslSocket.setEnabledCipherSuites(suites);
        if (debug) {
            System.out.println("StartTLS: Enabled cipher suites");
        }
    }

    // Connection must be quite for handshake to proceed

    try {
        if (debug) {
            System.out.println(
                    "StartTLS: Calling sslSocket.startHandshake");
        }
        sslSocket.startHandshake();
        if (debug) {
            System.out.println(
                    "StartTLS: + Finished sslSocket.startHandshake");
        }

        // Replace original streams with the new SSL streams
        ldapConnection.replaceStreams(sslSocket.getInputStream(),
            sslSocket.getOutputStream());
        if (debug) {
            System.out.println("StartTLS: Replaced IO Streams");
        }

    } catch (IOException e) {
        if (debug) {
            System.out.println("StartTLS: Got IO error during handshake");
            e.printStackTrace();
        }

        sslSocket.close();
        isClosed = true;
        throw e;   // pass up exception
    }

    return sslSocket;
}
 
Example 20
Source File: SSLSocketTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void test_SSLSocket_setSoWriteTimeout() throws Exception {
    if (StandardNames.IS_RI) {
        // RI does not support write timeout on sockets
        return;
    }

    final TestSSLContext c = TestSSLContext.create();
    SSLSocket client = (SSLSocket) c.clientContext.getSocketFactory().createSocket();

    // Try to make the client SO_SNDBUF size as small as possible
    // (it can default to 512k or even megabytes).  Note that
    // socket(7) says that the kernel will double the request to
    // leave room for its own book keeping and that the minimal
    // value will be 2048. Also note that tcp(7) says the value
    // needs to be set before connect(2).
    int sendBufferSize = 1024;
    client.setSendBufferSize(sendBufferSize);
    sendBufferSize = client.getSendBufferSize();

    // In jb-mr2 it was found that we need to also set SO_RCVBUF
    // to a minimal size or the write would not block. While
    // tcp(2) says the value has to be set before listen(2), it
    // seems fine to set it before accept(2).
    final int recvBufferSize = 128;
    c.serverSocket.setReceiveBufferSize(recvBufferSize);

    client.connect(new InetSocketAddress(c.host, c.port));

    final SSLSocket server = (SSLSocket) c.serverSocket.accept();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    Future<Void> future = executor.submit(new Callable<Void>() {
        @Override public Void call() throws Exception {
            server.startHandshake();
            return null;
        }
    });
    executor.shutdown();
    client.startHandshake();

    // Reflection is used so this can compile on the RI
    String expectedClassName = "com.android.org.conscrypt.OpenSSLSocketImpl";
    Class actualClass = client.getClass();
    assertEquals(expectedClassName, actualClass.getName());
    Method setSoWriteTimeout = actualClass.getMethod("setSoWriteTimeout",
                                                     new Class[] { Integer.TYPE });
    setSoWriteTimeout.invoke(client, 1);


    try {
        // Add extra space to the write to exceed the send buffer
        // size and cause the write to block.
        final int extra = 1;
        client.getOutputStream().write(new byte[sendBufferSize + extra]);
        fail();
    } catch (SocketTimeoutException expected) {
    }

    future.get();
    client.close();
    server.close();
    c.close();
}