Search in sources :

Example 91 with SocketChannel

use of java.nio.channels.SocketChannel in project h2o-3 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.BBP_BIG._size);
                SOCK.socket().bind(H2O.SELF._key);
            }
            // Block for TCP connection and setup to read from it.
            SocketChannel sock = SOCK.accept();
            ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
            ByteChannel wrappedSocket = socketChannelFactory.serverChannel(sock);
            bb.limit(bb.capacity());
            bb.position(0);
            while (bb.hasRemaining()) {
                // read first 8 bytes
                wrappedSocket.read(bb);
            }
            bb.flip();
            // 1 - small , 2 - big
            int chanType = bb.get();
            int port = bb.getChar();
            int sentinel = (0xFF) & bb.get();
            if (sentinel != 0xef) {
                if (H2O.SELF.getSecurityManager().securityEnabled) {
                    throw new IOException("Missing EOM sentinel when opening new SSL tcp channel.");
                } else {
                    throw H2O.fail("missing eom sentinel when opening new tcp channel");
                }
            }
            // todo compare against current cloud, refuse the con if no match
            // Do H2O.Intern in corresponding case branch, we can't do H2O.intern here since it wouldn't work
            // with ExternalFrameHandling ( we don't send the same information there as with the other communication)
            InetAddress inetAddress = sock.socket().getInetAddress();
            // Pass off the TCP connection to a separate reader thread
            switch(chanType) {
                case TCP_SMALL:
                    H2ONode h2o = H2ONode.intern(inetAddress, port);
                    new UDP_TCP_ReaderThread(h2o, wrappedSocket).start();
                    break;
                case TCP_BIG:
                    new TCPReaderThread(wrappedSocket, new AutoBuffer(wrappedSocket, inetAddress), inetAddress).start();
                    break;
                case TCP_EXTERNAL:
                    new ExternalFrameHandlerThread(wrappedSocket, new AutoBuffer(wrappedSocket, null)).start();
                    break;
                default:
                    throw H2O.fail("unexpected channel type " + chanType + ", only know 1 - Small, 2 - Big and 3 - ExternalFrameHandling");
            }
        } catch (java.nio.channels.AsynchronousCloseException ex) {
            // Socket closed for shutdown
            break;
        } catch (Exception e) {
            e.printStackTrace();
            // On any error from anybody, close all sockets & re-open
            Log.err("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) IOException(java.io.IOException) ByteBuffer(java.nio.ByteBuffer) IOException(java.io.IOException) ByteChannel(java.nio.channels.ByteChannel) InetAddress(java.net.InetAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 92 with SocketChannel

use of java.nio.channels.SocketChannel in project spring-boot by spring-projects.

the class TunnelClientTests method stopTriggersTunnelClose.

@Test
public void stopTriggersTunnelClose() throws Exception {
    TunnelClient client = new TunnelClient(this.listenPort, this.tunnelConnection);
    client.start();
    SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort));
    Thread.sleep(200);
    client.stop();
    assertThat(this.tunnelConnection.getOpenedTimes()).isEqualTo(1);
    assertThat(this.tunnelConnection.isOpen()).isFalse();
    assertThat(channel.read(ByteBuffer.allocate(1))).isEqualTo(-1);
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.Test)

Example 93 with SocketChannel

use of java.nio.channels.SocketChannel in project spring-boot by spring-projects.

the class TunnelClientTests method typicalTraffic.

@Test
public void typicalTraffic() throws Exception {
    TunnelClient client = new TunnelClient(this.listenPort, this.tunnelConnection);
    client.start();
    SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort));
    channel.write(ByteBuffer.wrap("hello".getBytes()));
    ByteBuffer buffer = ByteBuffer.allocate(5);
    channel.read(buffer);
    channel.close();
    this.tunnelConnection.verifyWritten("hello");
    assertThat(new String(buffer.array())).isEqualTo("olleh");
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ByteBuffer(java.nio.ByteBuffer) Test(org.junit.Test)

Example 94 with SocketChannel

use of java.nio.channels.SocketChannel in project spring-boot by spring-projects.

the class TunnelClientTests method addListener.

@Test
public void addListener() throws Exception {
    TunnelClient client = new TunnelClient(this.listenPort, this.tunnelConnection);
    TunnelClientListener listener = mock(TunnelClientListener.class);
    client.addListener(listener);
    client.start();
    SocketChannel channel = SocketChannel.open(new InetSocketAddress(this.listenPort));
    Thread.sleep(200);
    channel.close();
    client.getServerThread().stopAcceptingConnections();
    client.getServerThread().join(2000);
    verify(listener).onOpen(any(SocketChannel.class));
    verify(listener).onClose(any(SocketChannel.class));
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) Test(org.junit.Test)

Example 95 with SocketChannel

use of java.nio.channels.SocketChannel in project cassandra by apache.

the class OutboundTcpConnectionPool method newSocket.

// Closing the socket will close the underlying channel.
@SuppressWarnings("resource")
public static Socket newSocket(InetAddress endpoint) throws IOException {
    // zero means 'bind on any available port.'
    if (isEncryptedChannel(endpoint)) {
        return SSLFactory.getSocket(DatabaseDescriptor.getServerEncryptionOptions(), endpoint, DatabaseDescriptor.getSSLStoragePort());
    } else {
        SocketChannel channel = SocketChannel.open();
        channel.connect(new InetSocketAddress(endpoint, DatabaseDescriptor.getStoragePort()));
        return channel.socket();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress)

Aggregations

SocketChannel (java.nio.channels.SocketChannel)662 IOException (java.io.IOException)298 ServerSocketChannel (java.nio.channels.ServerSocketChannel)285 InetSocketAddress (java.net.InetSocketAddress)202 ByteBuffer (java.nio.ByteBuffer)163 SelectionKey (java.nio.channels.SelectionKey)105 Socket (java.net.Socket)87 Test (org.junit.Test)81 ClosedChannelException (java.nio.channels.ClosedChannelException)50 Selector (java.nio.channels.Selector)42 SocketAddress (java.net.SocketAddress)35 ServerSocket (java.net.ServerSocket)31 ClosedSelectorException (java.nio.channels.ClosedSelectorException)28 CancelledKeyException (java.nio.channels.CancelledKeyException)27 ConnectException (java.net.ConnectException)26 ArrayList (java.util.ArrayList)26 SocketTimeoutException (java.net.SocketTimeoutException)23 SelectableChannel (java.nio.channels.SelectableChannel)21 SocketException (java.net.SocketException)20 HashMap (java.util.HashMap)20