Search in sources :

Example 6 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testBlockedReadIdle.

@Test
public void testBlockedReadIdle() throws Exception {
    Socket client = newClient();
    InputStream clientInputStream = client.getInputStream();
    OutputStream clientOutputStream = client.getOutputStream();
    client.setSoTimeout(5000);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    clientOutputStream.write("HelloWorld".getBytes(StandardCharsets.UTF_8));
    // Verify echo server to client
    for (char c : "HelloWorld".toCharArray()) {
        int b = clientInputStream.read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    Assert.assertTrue(_lastEndPointLatch.await(1, TimeUnit.SECONDS));
    int idleTimeout = 500;
    _lastEndPoint.setIdleTimeout(idleTimeout);
    // Write 8 and cause block waiting for 10
    _blockAt = 10;
    clientOutputStream.write("12345678".getBytes(StandardCharsets.UTF_8));
    clientOutputStream.flush();
    // read until idle shutdown received
    long start = System.currentTimeMillis();
    int b = clientInputStream.read();
    assertEquals('E', b);
    long idle = System.currentTimeMillis() - start;
    assertTrue(idle > idleTimeout / 2);
    assertTrue(idle < idleTimeout * 2);
    for (char c : "E: 12345678".toCharArray()) {
        b = clientInputStream.read();
        assertTrue(b > 0);
        assertEquals(c, (char) b);
    }
    b = clientInputStream.read();
    assertEquals(-1, b);
    // But endpoint is still open.
    if (_lastEndPoint.isOpen())
        // Wait for another idle callback
        Thread.sleep(idleTimeout * 2);
    // endpoint is closed.
    assertFalse(_lastEndPoint.isOpen());
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) BufferedInputStream(java.io.BufferedInputStream) InputStream(java.io.InputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) Socket(java.net.Socket) Test(org.junit.Test)

Example 7 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectChannelEndPointTest method testWriteBlocked.

@Test
public void testWriteBlocked() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(10000);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    // Write client to server
    _writeCount = 10000;
    String data = "Now is the time for all good men to come to the aid of the party";
    client.getOutputStream().write(data.getBytes(StandardCharsets.UTF_8));
    BufferedInputStream in = new BufferedInputStream(client.getInputStream());
    int byteNum = 0;
    try {
        for (int i = 0; i < _writeCount; i++) {
            if (i % 1000 == 0)
                TimeUnit.MILLISECONDS.sleep(200);
            // Verify echo server to client
            for (int j = 0; j < data.length(); j++) {
                char c = data.charAt(j);
                int b = in.read();
                byteNum++;
                assertTrue(b > 0);
                assertEquals("test-" + i + "/" + j, c, (char) b);
            }
            if (i == 0)
                _lastEndPoint.setIdleTimeout(60000);
        }
    } catch (SocketTimeoutException e) {
        System.err.println("SelectorManager.dump() = " + _manager.dump());
        LOG.warn("Server: " + server);
        LOG.warn("Error reading byte #" + byteNum, e);
        throw e;
    }
    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) BufferedInputStream(java.io.BufferedInputStream) Socket(java.net.Socket) Test(org.junit.Test)

Example 8 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SslConnectionTest method testHelloWorld.

@Test
public void testHelloWorld() throws Exception {
    Socket client = newClient();
    client.setSoTimeout(60000);
    SocketChannel server = _connector.accept();
    server.configureBlocking(false);
    _manager.accept(server);
    client.getOutputStream().write("Hello".getBytes(StandardCharsets.UTF_8));
    byte[] buffer = new byte[1024];
    int len = client.getInputStream().read(buffer);
    Assert.assertEquals(5, len);
    Assert.assertEquals("Hello", new String(buffer, 0, len, StandardCharsets.UTF_8));
    _dispatches.set(0);
    client.getOutputStream().write("World".getBytes(StandardCharsets.UTF_8));
    len = 5;
    while (len > 0) len -= client.getInputStream().read(buffer);
    client.close();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Socket(java.net.Socket) SSLSocket(javax.net.ssl.SSLSocket) Test(org.junit.Test)

Example 9 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectorManager method chooseSelector.

private ManagedSelector chooseSelector(SelectableChannel channel) {
    // Ideally we would like to have all connections from the same client end
    // up on the same selector (to try to avoid smearing the data from a single
    // client over all cores), but because of proxies, the remote address may not
    // really be the client - so we have to hedge our bets to ensure that all
    // channels don't end up on the one selector for a proxy.
    ManagedSelector candidate1 = null;
    if (channel != null) {
        try {
            if (channel instanceof SocketChannel) {
                SocketAddress remote = ((SocketChannel) channel).getRemoteAddress();
                if (remote instanceof InetSocketAddress) {
                    byte[] addr = ((InetSocketAddress) remote).getAddress().getAddress();
                    if (addr != null) {
                        int s = addr[addr.length - 1] & 0xFF;
                        candidate1 = _selectors[s % getSelectorCount()];
                    }
                }
            }
        } catch (IOException x) {
            LOG.ignore(x);
        }
    }
    // The ++ increment here is not atomic, but it does not matter,
    // so long as the value changes sometimes, then connections will
    // be distributed over the available selectors.
    long s = _selectorIndex++;
    int index = (int) (s % getSelectorCount());
    ManagedSelector candidate2 = _selectors[index];
    if (candidate1 == null || candidate1.size() >= candidate2.size() * 2)
        return candidate2;
    return candidate1;
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) SocketAddress(java.net.SocketAddress) InetSocketAddress(java.net.InetSocketAddress)

Example 10 with SocketChannel

use of java.nio.channels.SocketChannel in project jetty.project by eclipse.

the class SelectChannelEndPointInterestsTest method testReadBlockedThenWriteBlockedThenReadableThenWritable.

@Test
public void testReadBlockedThenWriteBlockedThenReadableThenWritable() throws Exception {
    final AtomicInteger size = new AtomicInteger(1024 * 1024);
    final AtomicReference<Exception> failure = new AtomicReference<>();
    final CountDownLatch latch1 = new CountDownLatch(1);
    final CountDownLatch latch2 = new CountDownLatch(1);
    final AtomicBoolean writeBlocked = new AtomicBoolean();
    init(new Interested() {

        @Override
        public void onFillable(EndPoint endPoint, AbstractConnection connection) {
            ByteBuffer input = BufferUtil.allocate(2);
            int read = fill(endPoint, input);
            if (read == 1) {
                byte b = input.get();
                if (b == 1) {
                    connection.fillInterested();
                    ByteBuffer output = ByteBuffer.allocate(size.get());
                    endPoint.write(new Callback() {
                    }, output);
                    latch1.countDown();
                } else {
                    latch2.countDown();
                }
            } else {
                failure.set(new Exception("Unexpectedly read " + read + " bytes"));
            }
        }

        @Override
        public void onIncompleteFlush() {
            writeBlocked.set(true);
        }

        private int fill(EndPoint endPoint, ByteBuffer buffer) {
            try {
                return endPoint.fill(buffer);
            } catch (IOException x) {
                failure.set(x);
                return 0;
            }
        }
    });
    Socket client = new Socket();
    client.connect(connector.getLocalAddress());
    client.setSoTimeout(5000);
    SocketChannel server = connector.accept();
    server.configureBlocking(false);
    selectorManager.accept(server);
    OutputStream clientOutput = client.getOutputStream();
    clientOutput.write(1);
    clientOutput.flush();
    Assert.assertTrue(latch1.await(5, TimeUnit.SECONDS));
    // We do not read to keep the socket write blocked
    clientOutput.write(2);
    clientOutput.flush();
    Assert.assertTrue(latch2.await(5, TimeUnit.SECONDS));
    // Sleep before reading to allow waking up the server only for read
    Thread.sleep(1000);
    // Now read what was written, waking up the server for write
    InputStream clientInput = client.getInputStream();
    while (size.getAndDecrement() > 0) clientInput.read();
    client.close();
    Assert.assertNull(failure.get());
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InputStream(java.io.InputStream) OutputStream(java.io.OutputStream) AtomicReference(java.util.concurrent.atomic.AtomicReference) IOException(java.io.IOException) CountDownLatch(java.util.concurrent.CountDownLatch) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Callback(org.eclipse.jetty.util.Callback) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Socket(java.net.Socket) Test(org.junit.Test)

Aggregations

SocketChannel (java.nio.channels.SocketChannel)759 ServerSocketChannel (java.nio.channels.ServerSocketChannel)337 IOException (java.io.IOException)321 InetSocketAddress (java.net.InetSocketAddress)228 ByteBuffer (java.nio.ByteBuffer)188 SelectionKey (java.nio.channels.SelectionKey)126 Socket (java.net.Socket)101 Test (org.junit.Test)87 ClosedChannelException (java.nio.channels.ClosedChannelException)63 ServerSocket (java.net.ServerSocket)49 Selector (java.nio.channels.Selector)48 SocketAddress (java.net.SocketAddress)36 ClosedSelectorException (java.nio.channels.ClosedSelectorException)33 ConnectException (java.net.ConnectException)27 CancelledKeyException (java.nio.channels.CancelledKeyException)27 ArrayList (java.util.ArrayList)27 SocketTimeoutException (java.net.SocketTimeoutException)25 SelectableChannel (java.nio.channels.SelectableChannel)23 HashMap (java.util.HashMap)23 OutputStream (java.io.OutputStream)22