Search in sources :

Example 1 with SocketPolicy

use of okhttp3.mockwebserver.SocketPolicy in project okhttp by square.

the class URLConnectionTest method testServerClosesOutput.

private void testServerClosesOutput(SocketPolicy socketPolicy) throws Exception {
    server.enqueue(new MockResponse().setBody("This connection won't pool properly").setSocketPolicy(socketPolicy));
    MockResponse responseAfter = new MockResponse().setBody("This comes after a busted connection");
    server.enqueue(responseAfter);
    // Enqueue 2x because the broken connection may be reused.
    server.enqueue(responseAfter);
    HttpURLConnection connection1 = urlFactory.open(server.url("/a").url());
    connection1.setReadTimeout(100);
    assertContent("This connection won't pool properly", connection1);
    assertEquals(0, server.takeRequest().getSequenceNumber());
    // Give the server time to enact the socket policy if it's one that could happen after the
    // client has received the response.
    Thread.sleep(500);
    HttpURLConnection connection2 = urlFactory.open(server.url("/b").url());
    connection2.setReadTimeout(100);
    assertContent("This comes after a busted connection", connection2);
    // Check that a fresh connection was created, either immediately or after attempting reuse.
    RecordedRequest requestAfter = server.takeRequest();
    if (server.getRequestCount() == 3) {
        // The failure consumed a response.
        requestAfter = server.takeRequest();
    }
    // sequence number 0 means the HTTP socket connection was not reused
    assertEquals(0, requestAfter.getSequenceNumber());
}
Also used : RecordedRequest(okhttp3.mockwebserver.RecordedRequest) MockResponse(okhttp3.mockwebserver.MockResponse) HttpURLConnection(java.net.HttpURLConnection) OkHttpURLConnection(okhttp3.internal.huc.OkHttpURLConnection)

Example 2 with SocketPolicy

use of okhttp3.mockwebserver.SocketPolicy in project okhttp by square.

the class MockWebServer method start.

/**
   * Starts the server and binds to the given socket address.
   *
   * @param inetSocketAddress the socket address to bind the server on
   */
private synchronized void start(InetSocketAddress inetSocketAddress) throws IOException {
    if (started)
        throw new IllegalStateException("start() already called");
    started = true;
    executor = Executors.newCachedThreadPool(Util.threadFactory("MockWebServer", false));
    this.inetSocketAddress = inetSocketAddress;
    serverSocket = serverSocketFactory.createServerSocket();
    // Reuse if the user specified a port
    serverSocket.setReuseAddress(inetSocketAddress.getPort() != 0);
    serverSocket.bind(inetSocketAddress, 50);
    port = serverSocket.getLocalPort();
    executor.execute(new NamedRunnable("MockWebServer %s", port) {

        @Override
        protected void execute() {
            try {
                logger.info(MockWebServer.this + " starting to accept connections");
                acceptConnections();
            } catch (Throwable e) {
                logger.log(Level.WARNING, MockWebServer.this + " failed unexpectedly", e);
            }
            // Release all sockets and all threads, even if any close fails.
            closeQuietly(serverSocket);
            for (Iterator<Socket> s = openClientSockets.iterator(); s.hasNext(); ) {
                closeQuietly(s.next());
                s.remove();
            }
            for (Iterator<Http2Connection> s = openConnections.iterator(); s.hasNext(); ) {
                closeQuietly(s.next());
                s.remove();
            }
            dispatcher.shutdown();
            executor.shutdown();
        }

        private void acceptConnections() throws Exception {
            while (true) {
                Socket socket;
                try {
                    socket = serverSocket.accept();
                } catch (SocketException e) {
                    logger.info(MockWebServer.this + " done accepting connections: " + e.getMessage());
                    return;
                }
                SocketPolicy socketPolicy = dispatcher.peek().getSocketPolicy();
                if (socketPolicy == DISCONNECT_AT_START) {
                    dispatchBookkeepingRequest(0, socket);
                    socket.close();
                } else {
                    openClientSockets.add(socket);
                    serveConnection(socket);
                }
            }
        }
    });
}
Also used : SocketException(java.net.SocketException) Iterator(java.util.Iterator) NamedRunnable(okhttp3.internal.NamedRunnable) InterruptedIOException(java.io.InterruptedIOException) SocketException(java.net.SocketException) IOException(java.io.IOException) CertificateException(java.security.cert.CertificateException) ProtocolException(java.net.ProtocolException) SSLSocket(javax.net.ssl.SSLSocket) ServerSocket(java.net.ServerSocket) RealWebSocket(okhttp3.internal.ws.RealWebSocket) Socket(java.net.Socket)

Aggregations

IOException (java.io.IOException)1 InterruptedIOException (java.io.InterruptedIOException)1 HttpURLConnection (java.net.HttpURLConnection)1 ProtocolException (java.net.ProtocolException)1 ServerSocket (java.net.ServerSocket)1 Socket (java.net.Socket)1 SocketException (java.net.SocketException)1 CertificateException (java.security.cert.CertificateException)1 Iterator (java.util.Iterator)1 SSLSocket (javax.net.ssl.SSLSocket)1 NamedRunnable (okhttp3.internal.NamedRunnable)1 OkHttpURLConnection (okhttp3.internal.huc.OkHttpURLConnection)1 RealWebSocket (okhttp3.internal.ws.RealWebSocket)1 MockResponse (okhttp3.mockwebserver.MockResponse)1 RecordedRequest (okhttp3.mockwebserver.RecordedRequest)1