Search in sources :

Example 1 with SocketTimeoutException

use of java.net.SocketTimeoutException in project jetty.project by eclipse.

the class HttpClientTransportOverHTTP2Test method testClientStopsServerDoesNotCloseClientCloses.

@Test
public void testClientStopsServerDoesNotCloseClientCloses() throws Exception {
    try (ServerSocket server = new ServerSocket(0)) {
        List<Session> sessions = new ArrayList<>();
        HTTP2Client h2Client = new HTTP2Client();
        HttpClient client = new HttpClient(new HttpClientTransportOverHTTP2(h2Client) {

            @Override
            protected HttpConnectionOverHTTP2 newHttpConnection(HttpDestination destination, Session session) {
                sessions.add(session);
                return super.newHttpConnection(destination, session);
            }
        }, null);
        QueuedThreadPool clientExecutor = new QueuedThreadPool();
        clientExecutor.setName("client");
        client.setExecutor(clientExecutor);
        client.start();
        CountDownLatch resultLatch = new CountDownLatch(1);
        client.newRequest("localhost", server.getLocalPort()).send(result -> {
            if (result.getResponse().getStatus() == HttpStatus.OK_200)
                resultLatch.countDown();
        });
        ByteBufferPool byteBufferPool = new MappedByteBufferPool();
        ByteBufferPool.Lease lease = new ByteBufferPool.Lease(byteBufferPool);
        Generator generator = new Generator(byteBufferPool);
        try (Socket socket = server.accept()) {
            socket.setSoTimeout(1000);
            OutputStream output = socket.getOutputStream();
            InputStream input = socket.getInputStream();
            ServerParser parser = new ServerParser(byteBufferPool, new ServerParser.Listener.Adapter() {

                @Override
                public void onHeaders(HeadersFrame request) {
                    // Server's preface.
                    generator.control(lease, new SettingsFrame(new HashMap<>(), false));
                    // Reply to client's SETTINGS.
                    generator.control(lease, new SettingsFrame(new HashMap<>(), true));
                    // Response.
                    MetaData.Response metaData = new MetaData.Response(HttpVersion.HTTP_2, HttpStatus.OK_200, new HttpFields());
                    HeadersFrame response = new HeadersFrame(request.getStreamId(), metaData, null, true);
                    generator.control(lease, response);
                    try {
                        // Write the frames.
                        for (ByteBuffer buffer : lease.getByteBuffers()) output.write(BufferUtil.toArray(buffer));
                    } catch (Throwable x) {
                        x.printStackTrace();
                    }
                }
            }, 4096, 8192);
            byte[] bytes = new byte[1024];
            while (true) {
                try {
                    int read = input.read(bytes);
                    if (read < 0)
                        Assert.fail();
                    parser.parse(ByteBuffer.wrap(bytes, 0, read));
                } catch (SocketTimeoutException x) {
                    break;
                }
            }
            Assert.assertTrue(resultLatch.await(5, TimeUnit.SECONDS));
            // The client will send a GO_AWAY, but the server will not close.
            client.stop();
            // Give some time to process the stop/close operations.
            Thread.sleep(1000);
            Assert.assertTrue(h2Client.getBeans(Session.class).isEmpty());
            for (Session session : sessions) {
                Assert.assertTrue(session.isClosed());
                Assert.assertTrue(((HTTP2Session) session).isDisconnected());
            }
        }
    }
}
Also used : ByteBufferPool(org.eclipse.jetty.io.ByteBufferPool) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ServerSessionListener(org.eclipse.jetty.http2.api.server.ServerSessionListener) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) HeadersFrame(org.eclipse.jetty.http2.frames.HeadersFrame) SettingsFrame(org.eclipse.jetty.http2.frames.SettingsFrame) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) MetaData(org.eclipse.jetty.http.MetaData) HttpFields(org.eclipse.jetty.http.HttpFields) ServerParser(org.eclipse.jetty.http2.parser.ServerParser) InputStream(java.io.InputStream) ServerSocket(java.net.ServerSocket) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) MappedByteBufferPool(org.eclipse.jetty.io.MappedByteBufferPool) ContentResponse(org.eclipse.jetty.client.api.ContentResponse) HttpServletResponse(javax.servlet.http.HttpServletResponse) SocketTimeoutException(java.net.SocketTimeoutException) HttpClient(org.eclipse.jetty.client.HttpClient) HTTP2Client(org.eclipse.jetty.http2.client.HTTP2Client) HttpDestination(org.eclipse.jetty.client.HttpDestination) ServerSocket(java.net.ServerSocket) Socket(java.net.Socket) HTTP2Session(org.eclipse.jetty.http2.HTTP2Session) Session(org.eclipse.jetty.http2.api.Session) Generator(org.eclipse.jetty.http2.generator.Generator) Test(org.junit.Test)

Example 2 with SocketTimeoutException

use of java.net.SocketTimeoutException in project jetty.project by eclipse.

the class AbstractServerTest method parseResponse.

protected boolean parseResponse(Socket client, Parser parser, long timeout) throws IOException {
    byte[] buffer = new byte[2048];
    InputStream input = client.getInputStream();
    client.setSoTimeout((int) timeout);
    while (true) {
        try {
            int read = input.read(buffer);
            if (read < 0)
                return true;
            parser.parse(ByteBuffer.wrap(buffer, 0, read));
            if (client.isClosed())
                return true;
        } catch (SocketTimeoutException x) {
            return false;
        }
    }
}
Also used : SocketTimeoutException(java.net.SocketTimeoutException) InputStream(java.io.InputStream)

Example 3 with SocketTimeoutException

use of java.net.SocketTimeoutException in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testShutdown.

@Test
public void testShutdown() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(500);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    // wait for read timeout
    long start = System.currentTimeMillis();
    try {
        client.getInputStream().read();
        Assert.fail();
    } catch (SocketTimeoutException e) {
        assertTrue(System.currentTimeMillis() - start >= 400);
    }
    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));
    client.shutdownOutput();
    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    // Read close
    assertEquals(-1, client.getInputStream().read());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketTimeoutException(java.net.SocketTimeoutException) Socket(java.net.Socket) Test(org.junit.Test)

Example 4 with SocketTimeoutException

use of java.net.SocketTimeoutException in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testRejectedExecution.

// TODO make this test reliable
@Test
@Ignore
public void testRejectedExecution() throws Exception {
    _manager.stop();
    _threadPool.stop();
    final CountDownLatch latch = new CountDownLatch(1);
    BlockingQueue<Runnable> q = new ArrayBlockingQueue<>(4);
    _threadPool = new QueuedThreadPool(4, 4, 60000, q);
    _manager = new SelectorManager(_threadPool, _scheduler, 1) {

        @Override
        protected EndPoint newEndPoint(SelectableChannel channel, ManagedSelector selector, SelectionKey selectionKey) throws IOException {
            SocketChannelEndPoint endp = new SocketChannelEndPoint(channel, selector, selectionKey, getScheduler());
            _lastEndPoint = endp;
            _lastEndPointLatch.countDown();
            return endp;
        }

        @Override
        public Connection newConnection(SelectableChannel channel, EndPoint endpoint, Object attachment) throws IOException {
            return new TestConnection(endpoint, latch);
        }
    };
    _threadPool.start();
    _manager.start();
    AtomicInteger timeout = new AtomicInteger();
    AtomicInteger rejections = new AtomicInteger();
    AtomicInteger echoed = new AtomicInteger();
    CountDownLatch closed = new CountDownLatch(20);
    for (int i = 0; i < 20; i++) {
        new Thread() {

            public void run() {
                try (Socket client = newClient()) {
                    client.setSoTimeout(5000);
                    SocketChannel server = _connector.accept();
                    server.configureBlocking(false);
                    _manager.accept(server);
                    // Write client to server
                    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
                    client.getOutputStream().flush();
                    client.shutdownOutput();
                    // Verify echo server to client
                    for (char c : "HelloWorld".toCharArray()) {
                        int b = client.getInputStream().read();
                        assertTrue(b > 0);
                        assertEquals(c, (char) b);
                    }
                    assertEquals(-1, client.getInputStream().read());
                    echoed.incrementAndGet();
                } catch (SocketTimeoutException x) {
                    x.printStackTrace();
                    timeout.incrementAndGet();
                } catch (Throwable x) {
                    rejections.incrementAndGet();
                } finally {
                    closed.countDown();
                }
            }
        }.start();
    }
    // unblock the handling
    latch.countDown();
    // wait for all clients to complete or fail
    closed.await();
    // assert some clients must have been rejected
    Assert.assertThat(rejections.get(), Matchers.greaterThan(0));
    // but not all of them
    Assert.assertThat(rejections.get(), Matchers.lessThan(20));
    // none should have timed out
    Assert.assertThat(timeout.get(), Matchers.equalTo(0));
    // and the rest should have worked
    Assert.assertThat(echoed.get(), Matchers.equalTo(20 - rejections.get()));
    // and the selector is still working for new requests
    try (Socket client = newClient()) {
        client.setSoTimeout(5000);
        SocketChannel server = _connector.accept();
        server.configureBlocking(false);
        _manager.accept(server);
        // Write client to server
        client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
        client.getOutputStream().flush();
        client.shutdownOutput();
        // Verify echo server to client
        for (char c : "HelloWorld".toCharArray()) {
            int b = client.getInputStream().read();
            assertTrue(b > 0);
            assertEquals(c, (char) b);
        }
        assertEquals(-1, client.getInputStream().read());
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) SocketTimeoutException(java.net.SocketTimeoutException) ArrayBlockingQueue(java.util.concurrent.ArrayBlockingQueue) SelectableChannel(java.nio.channels.SelectableChannel) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Ignore(org.junit.Ignore) Test(org.junit.Test)

Example 5 with SocketTimeoutException

use of java.net.SocketTimeoutException in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testEcho.

@Test
public void testEcho() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(60000);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    client.getOutputStream().write("HelloWorld".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
        int b = client.getInputStream().read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    // wait for read timeout
    client.setSoTimeout(500);
    long start = System.currentTimeMillis();
    try {
        client.getInputStream().read();
        Assert.fail();
    } catch (SocketTimeoutException e) {
        long duration = System.currentTimeMillis() - start;
        Assert.assertThat("timeout duration", duration, greaterThanOrEqualTo(400L));
    }
    // write then shutdown
    client.getOutputStream().write("Goodbye Cruel TLS".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "Goodbye Cruel TLS".toCharArray()) {
        int b = client.getInputStream().read();
        Assert.assertThat("expect valid char integer", b, greaterThan(0));
        assertEquals("expect characters to be same", c, (char) b);
    }
    client.close();
    for (int i = 0; i < 10; ++i) {
        if (server.isOpen())
            Thread.sleep(10);
        else
            break;
    }
    assertFalse(server.isOpen());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketTimeoutException(java.net.SocketTimeoutException) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

SocketTimeoutException (java.net.SocketTimeoutException)712 IOException (java.io.IOException)414 Test (org.junit.Test)139 Socket (java.net.Socket)103 SocketException (java.net.SocketException)99 ServerSocket (java.net.ServerSocket)79 InputStream (java.io.InputStream)77 ConnectException (java.net.ConnectException)69 UnknownHostException (java.net.UnknownHostException)64 InetSocketAddress (java.net.InetSocketAddress)60 URL (java.net.URL)50 EOFException (java.io.EOFException)47 HttpURLConnection (java.net.HttpURLConnection)46 InterruptedIOException (java.io.InterruptedIOException)40 ArrayList (java.util.ArrayList)40 ConnectTimeoutException (org.apache.http.conn.ConnectTimeoutException)40 MalformedURLException (java.net.MalformedURLException)39 InputStreamReader (java.io.InputStreamReader)37 OutputStream (java.io.OutputStream)35 HashMap (java.util.HashMap)35