Search in sources :

Example 71 with ServerSocketChannel

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

the class ServerConnector method close.

@Override
public void close() {
    ServerSocketChannel serverChannel = _acceptChannel;
    _acceptChannel = null;
    if (serverChannel != null) {
        removeBean(serverChannel);
        // If the interrupt did not close it, we should close it
        if (serverChannel.isOpen()) {
            try {
                serverChannel.close();
            } catch (IOException e) {
                LOG.warn(e);
            }
        }
    }
    // super.close();
    _localPort = -2;
}
Also used : IOException(java.io.IOException) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 72 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project gitblit by gitblit.

the class FanoutNioService method listen.

@Override
protected void listen() throws IOException {
    while (selector.select(serviceTimeout) > 0) {
        Set<SelectionKey> keys = selector.selectedKeys();
        Iterator<SelectionKey> keyItr = keys.iterator();
        while (keyItr.hasNext()) {
            SelectionKey key = keyItr.next();
            if (key.isAcceptable()) {
                // new fanout client connection
                ServerSocketChannel sch = (ServerSocketChannel) key.channel();
                try {
                    SocketChannel ch = sch.accept();
                    ch.configureBlocking(false);
                    configureClientSocket(ch.socket());
                    FanoutNioConnection connection = new FanoutNioConnection(ch);
                    addConnection(connection);
                    // register to send the queued message
                    ch.register(selector, SelectionKey.OP_WRITE, connection);
                } catch (IOException e) {
                    logger.error("error accepting fanout connection", e);
                }
            } else if (key.isReadable()) {
                // read fanout client request
                SocketChannel ch = (SocketChannel) key.channel();
                FanoutNioConnection connection = (FanoutNioConnection) key.attachment();
                try {
                    connection.read(ch, isStrictRequestTermination());
                    int replies = 0;
                    Iterator<String> reqItr = connection.requestQueue.iterator();
                    while (reqItr.hasNext()) {
                        String req = reqItr.next();
                        String reply = processRequest(connection, req);
                        reqItr.remove();
                        if (reply != null) {
                            replies++;
                        }
                    }
                    if (replies > 0) {
                        // register to send the replies to requests
                        ch.register(selector, SelectionKey.OP_WRITE, connection);
                    } else {
                        // re-register for next read
                        ch.register(selector, SelectionKey.OP_READ, connection);
                    }
                } catch (IOException e) {
                    logger.error(MessageFormat.format("fanout connection {0} error: {1}", connection.id, e.getMessage()));
                    removeConnection(connection);
                    closeClientSocket(connection.id, ch);
                }
            } else if (key.isWritable()) {
                // asynchronous reply to fanout client request
                SocketChannel ch = (SocketChannel) key.channel();
                FanoutNioConnection connection = (FanoutNioConnection) key.attachment();
                try {
                    connection.write(ch);
                    if (hasConnection(connection)) {
                        // register for next read
                        ch.register(selector, SelectionKey.OP_READ, connection);
                    } else {
                        // Connection was rejected due to load or
                        // some other reason. Close it.
                        closeClientSocket(connection.id, ch);
                    }
                } catch (IOException e) {
                    logger.error(MessageFormat.format("fanout connection {0}: {1}", connection.id, e.getMessage()));
                    removeConnection(connection);
                    closeClientSocket(connection.id, ch);
                }
            }
            keyItr.remove();
        }
    }
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) Iterator(java.util.Iterator) IOException(java.io.IOException) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 73 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project h2o-2 by h2oai.

the class TCPReceiverThread method run.

// The Run Method.
// Started by main() on a single thread, this code manages reading TCP requests
@SuppressWarnings("resource")
public void run() {
    Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
    ServerSocketChannel errsock = null;
    boolean saw_error = false;
    while (true) {
        try {
            // Cleanup from any prior socket failures.  Rare unless we're really sick.
            if (errsock != null) {
                // One time attempt a socket close
                final ServerSocketChannel tmp2 = errsock;
                errsock = null;
                // Could throw, but errsock cleared for next pass
                tmp2.close();
            }
            // prevent deny-of-service endless socket-creates
            if (saw_error)
                Thread.sleep(100);
            saw_error = false;
            // More common-case setup of a ServerSocket
            if (SOCK == null) {
                SOCK = ServerSocketChannel.open();
                SOCK.socket().setReceiveBufferSize(AutoBuffer.BBSIZE);
                SOCK.socket().bind(H2O.SELF._key);
            }
            // Block for TCP connection and setup to read from it.
            SocketChannel sock = SOCK.accept();
            // Pass off the TCP connection to a separate reader thread
            new TCPReaderThread(sock, new AutoBuffer(sock)).start();
        } catch (java.nio.channels.AsynchronousCloseException ex) {
            // Socket closed for shutdown
            break;
        } catch (Exception e) {
            // On any error from anybody, close all sockets & re-open
            Log.err("Retrying after IO error on TCP port " + H2O.H2O_PORT + ": ", e);
            saw_error = true;
            // Signal error recovery on the next loop
            errsock = SOCK;
            // Signal error recovery on the next loop
            SOCK = null;
        }
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 74 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project h2o-3 by h2oai.

the class SSLSocketChannelFactoryTest method shouldHandshake.

@Test
public void shouldHandshake() throws IOException, SSLContextException, BrokenBarrierException, InterruptedException {
    SSLProperties props = new SSLProperties();
    props.put("h2o_ssl_protocol", SecurityUtils.defaultTLSVersion());
    props.put("h2o_ssl_jks_internal", getFile("src/test/resources/keystore.jks").getPath());
    props.put("h2o_ssl_jks_password", "password");
    props.put("h2o_ssl_jts", getFile("src/test/resources/cacerts.jks").getPath());
    props.put("h2o_ssl_jts_password", "password");
    final SSLSocketChannelFactory factory = new SSLSocketChannelFactory(props);
    final CyclicBarrier barrier = new CyclicBarrier(2);
    final CyclicBarrier testOne = new CyclicBarrier(2);
    final CyclicBarrier testTwo = new CyclicBarrier(2);
    final CyclicBarrier testThree = new CyclicBarrier(2);
    final boolean[] hs = new boolean[] { true };
    Thread client = new ClientThread(factory, testOne, testTwo, testThree, barrier);
    client.setDaemon(false);
    client.start();
    try {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.socket().setReceiveBufferSize(64 * 1024);
        while (true) {
            try {
                serverSocketChannel.socket().bind(new InetSocketAddress(port));
                break;
            } catch (BindException e) {
                port++;
            }
        }
        barrier.await();
        SocketChannel sock = serverSocketChannel.accept();
        barrier.reset();
        SSLSocketChannel wrappedChannel = (SSLSocketChannel) factory.wrapServerChannel(sock);
        assertTrue(wrappedChannel.isHandshakeComplete());
        // FIRST TEST: SSL -> SSL SMALL COMMUNICATION
        ByteBuffer readBuffer = ByteBuffer.allocate(12);
        while (readBuffer.hasRemaining()) {
            wrappedChannel.read(readBuffer);
        }
        readBuffer.flip();
        byte[] dst = new byte[12];
        readBuffer.get(dst, 0, 12);
        readBuffer.clear();
        assertEquals("hello, world", new String(dst, "UTF-8"));
        testOne.await();
        // SECOND TEST: SSL -> SSL BIG COMMUNICATION
        int read = 0;
        byte[] dstBig = new byte[16];
        ByteBuffer readBufferBig = ByteBuffer.allocate(1024);
        while (read < 5 * 64 * 1024) {
            while (readBufferBig.position() < 16) {
                wrappedChannel.read(readBufferBig);
            }
            readBufferBig.flip();
            readBufferBig.get(dstBig, 0, 16);
            if (!readBufferBig.hasRemaining()) {
                readBufferBig.clear();
            } else {
                readBufferBig.compact();
            }
            assertEquals("hello, world" + (read % 9) + "!!!", new String(dstBig, "UTF-8"));
            read += 16;
        }
        testTwo.await();
        // THIRD TEST: NON-SSL -> SSL COMMUNICATION
        try {
            while (readBuffer.hasRemaining()) {
                wrappedChannel.read(readBuffer);
            }
            fail();
        } catch (SSLException e) {
        // PASSED
        }
        assertTrue(wrappedChannel.getEngine().isInboundDone());
        testThree.await();
        // FOURTH TEST: SSL -> NON-SSL COMMUNICATION
        readBuffer.clear();
        while (readBuffer.hasRemaining()) {
            sock.read(readBuffer);
        }
        readBuffer.flip();
        readBuffer.get(dst, 0, 12);
        readBuffer.clear();
        assertNotEquals("hello, world", new String(dst, "UTF-8"));
    } catch (IOException | InterruptedException | BrokenBarrierException e) {
        e.printStackTrace();
    }
    barrier.await();
    assertTrue("One of the handshakes failed!", hs[0]);
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) BrokenBarrierException(java.util.concurrent.BrokenBarrierException) InetSocketAddress(java.net.InetSocketAddress) BindException(java.net.BindException) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) SSLException(javax.net.ssl.SSLException) CyclicBarrier(java.util.concurrent.CyclicBarrier) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Test(org.junit.Test)

Example 75 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project tomcat by apache.

the class NioReceiver method listen.

/**
     * Get data from channel and store in byte array
     * send it to cluster
     * @throws IOException IO error
     */
protected void listen() throws Exception {
    if (doListen()) {
        log.warn(sm.getString("nioReceiver.alreadyStarted"));
        return;
    }
    setListen(true);
    // Avoid NPEs if selector is set to null on stop.
    Selector selector = this.selector.get();
    if (selector != null && datagramChannel != null) {
        //max size for a datagram packet
        ObjectReader oreader = new ObjectReader(MAX_UDP_SIZE);
        registerChannel(selector, datagramChannel, SelectionKey.OP_READ, oreader);
    }
    while (doListen() && selector != null) {
        // selected set contains keys of the ready channels
        try {
            events();
            socketTimeouts();
            int n = selector.select(getSelectorTimeout());
            if (n == 0) {
                // nothing to do
                continue;
            }
            // get an iterator over the set of selected keys
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            // look at each key in the selected set
            while (it != null && it.hasNext()) {
                SelectionKey key = it.next();
                // Is a new connection coming in?
                if (key.isAcceptable()) {
                    ServerSocketChannel server = (ServerSocketChannel) key.channel();
                    SocketChannel channel = server.accept();
                    channel.socket().setReceiveBufferSize(getTxBufSize());
                    channel.socket().setSendBufferSize(getTxBufSize());
                    channel.socket().setTcpNoDelay(getTcpNoDelay());
                    channel.socket().setKeepAlive(getSoKeepAlive());
                    channel.socket().setOOBInline(getOoBInline());
                    channel.socket().setReuseAddress(getSoReuseAddress());
                    channel.socket().setSoLinger(getSoLingerOn(), getSoLingerTime());
                    channel.socket().setSoTimeout(getTimeout());
                    Object attach = new ObjectReader(channel);
                    registerChannel(selector, channel, SelectionKey.OP_READ, attach);
                }
                // is there data to read on this channel?
                if (key.isReadable()) {
                    readDataFromSocket(key);
                } else {
                    key.interestOps(key.interestOps() & (~SelectionKey.OP_WRITE));
                }
                // remove key from selected set, it's been handled
                it.remove();
            }
        } catch (java.nio.channels.ClosedSelectorException cse) {
        // ignore is normal at shutdown or stop listen socket
        } catch (java.nio.channels.CancelledKeyException nx) {
            log.warn(sm.getString("nioReceiver.clientDisconnect"));
        } catch (Throwable t) {
            ExceptionUtils.handleThrowable(t);
            log.error(sm.getString("nioReceiver.requestError"), t);
        }
    }
    serverChannel.close();
    if (datagramChannel != null) {
        try {
            datagramChannel.close();
        } catch (Exception iox) {
            if (log.isDebugEnabled())
                log.debug("Unable to close datagram channel.", iox);
        }
        datagramChannel = null;
    }
    closeSelector();
}
Also used : SelectionKey(java.nio.channels.SelectionKey) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) CancelledKeyException(java.nio.channels.CancelledKeyException) CancelledKeyException(java.nio.channels.CancelledKeyException) IOException(java.io.IOException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) ClosedSelectorException(java.nio.channels.ClosedSelectorException) ObjectReader(org.apache.catalina.tribes.io.ObjectReader) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Aggregations

ServerSocketChannel (java.nio.channels.ServerSocketChannel)122 SocketChannel (java.nio.channels.SocketChannel)65 InetSocketAddress (java.net.InetSocketAddress)55 IOException (java.io.IOException)43 ByteBuffer (java.nio.ByteBuffer)26 ServerSocket (java.net.ServerSocket)19 SelectionKey (java.nio.channels.SelectionKey)19 Selector (java.nio.channels.Selector)13 Socket (java.net.Socket)12 Test (org.junit.Test)11 ClosedChannelException (java.nio.channels.ClosedChannelException)10 InetAddress (java.net.InetAddress)9 ClosedSelectorException (java.nio.channels.ClosedSelectorException)8 SocketException (java.net.SocketException)6 Benchmark (org.openjdk.jmh.annotations.Benchmark)6 ClosedByInterruptException (java.nio.channels.ClosedByInterruptException)5 URISyntaxException (java.net.URISyntaxException)4 CancelledKeyException (java.nio.channels.CancelledKeyException)4 IllegalBlockingModeException (java.nio.channels.IllegalBlockingModeException)4 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4