Search in sources :

Example 86 with SocketChannel

use of java.nio.channels.SocketChannel in project j2objc by google.

the class SocketTest method checkSocketLocalAndRemoteAddresses.

// http://code.google.com/p/android/issues/detail?id=3123
// http://code.google.com/p/android/issues/detail?id=1933
/* Fails on machines with IPv6 connections, both on JRE and j2objc.
    public void test_socketLocalAndRemoteAddresses() throws Exception {
        checkSocketLocalAndRemoteAddresses(false);
        checkSocketLocalAndRemoteAddresses(true);
    }
    */
public void checkSocketLocalAndRemoteAddresses(boolean setOptions) throws Exception {
    InetAddress host = InetAddress.getLocalHost();
    // Open a local server port.
    ServerSocketChannel ssc = ServerSocketChannel.open();
    InetSocketAddress listenAddr = new InetSocketAddress(host, 0);
    ssc.bind(listenAddr, 0);
    ServerSocket ss = ssc.socket();
    // Open a socket to the local port.
    SocketChannel out = SocketChannel.open();
    out.configureBlocking(false);
    if (setOptions) {
        out.socket().setTcpNoDelay(false);
    }
    InetSocketAddress addr = new InetSocketAddress(host, ssc.socket().getLocalPort());
    out.connect(addr);
    while (!out.finishConnect()) {
        Thread.sleep(1);
    }
    SocketChannel in = ssc.accept();
    if (setOptions) {
        in.socket().setTcpNoDelay(false);
    }
    InetSocketAddress listenAddress = (InetSocketAddress) in.getLocalAddress();
    InetSocketAddress outRemoteAddress = (InetSocketAddress) out.socket().getRemoteSocketAddress();
    InetSocketAddress outLocalAddress = (InetSocketAddress) out.socket().getLocalSocketAddress();
    InetSocketAddress inLocalAddress = (InetSocketAddress) in.socket().getLocalSocketAddress();
    InetSocketAddress inRemoteAddress = (InetSocketAddress) in.socket().getRemoteSocketAddress();
    //        System.err.println("listenAddress: " + listenAddr);
    //        System.err.println("inLocalAddress: " + inLocalAddress);
    //        System.err.println("inRemoteAddress: " + inRemoteAddress);
    //        System.err.println("outLocalAddress: " + outLocalAddress);
    //        System.err.println("outRemoteAddress: " + outRemoteAddress);
    assertFalse(ssc.socket().isClosed());
    assertTrue(ssc.socket().isBound());
    assertTrue(in.isConnected());
    assertTrue(in.socket().isConnected());
    assertTrue(out.socket().isConnected());
    assertTrue(out.isConnected());
    in.close();
    out.close();
    ssc.close();
    assertTrue(ssc.socket().isClosed());
    assertTrue(ssc.socket().isBound());
    assertFalse(in.isConnected());
    assertFalse(in.socket().isConnected());
    assertFalse(out.socket().isConnected());
    assertFalse(out.isConnected());
    assertNull(in.socket().getRemoteSocketAddress());
    assertNull(out.socket().getRemoteSocketAddress());
    // As per docs and RI - server socket local address methods continue to return the bind()
    // addresses even after close().
    assertEquals(listenAddress, ssc.socket().getLocalSocketAddress());
    // As per docs and RI - socket local address methods return the wildcard address before
    // bind() and after close(), but the port will be the same as it was before close().
    InetSocketAddress inLocalAddressAfterClose = (InetSocketAddress) in.socket().getLocalSocketAddress();
    assertTrue(inLocalAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(inLocalAddress.getPort(), inLocalAddressAfterClose.getPort());
    InetSocketAddress outLocalAddressAfterClose = (InetSocketAddress) out.socket().getLocalSocketAddress();
    assertTrue(outLocalAddressAfterClose.getAddress().isAnyLocalAddress());
    assertEquals(outLocalAddress.getPort(), outLocalAddressAfterClose.getPort());
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) InetSocketAddress(java.net.InetSocketAddress) ServerSocket(java.net.ServerSocket) InetAddress(java.net.InetAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 87 with SocketChannel

use of java.nio.channels.SocketChannel in project hazelcast by hazelcast.

the class ClientConnectionManagerImpl method createSocketConnection.

protected ClientConnection createSocketConnection(final Address address) throws IOException {
    if (!alive) {
        throw new HazelcastException("ConnectionManager is not active!");
    }
    SocketChannel socketChannel = null;
    try {
        socketChannel = SocketChannel.open();
        Socket socket = socketChannel.socket();
        socket.setKeepAlive(socketOptions.isKeepAlive());
        socket.setTcpNoDelay(socketOptions.isTcpNoDelay());
        socket.setReuseAddress(socketOptions.isReuseAddress());
        if (socketOptions.getLingerSeconds() > 0) {
            socket.setSoLinger(true, socketOptions.getLingerSeconds());
        }
        int bufferSize = getBufferSize();
        socket.setSendBufferSize(bufferSize);
        socket.setReceiveBufferSize(bufferSize);
        InetSocketAddress inetSocketAddress = address.getInetSocketAddress();
        socketChannel.socket().connect(inetSocketAddress, connectionTimeout);
        SocketChannelWrapper socketChannelWrapper = socketChannelWrapperFactory.wrapSocketChannel(socketChannel, true);
        final ClientConnection clientConnection = new ClientConnection(client, ioThreadingModel, connectionIdGen.incrementAndGet(), socketChannelWrapper);
        socketChannel.configureBlocking(true);
        if (socketInterceptor != null) {
            socketInterceptor.onConnect(socket);
        }
        socketChannel.configureBlocking(ioThreadingModel.isBlocking());
        socket.setSoTimeout(0);
        clientConnection.start();
        return clientConnection;
    } catch (Exception e) {
        if (socketChannel != null) {
            socketChannel.close();
        }
        throw ExceptionUtil.rethrow(e, IOException.class);
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) HazelcastException(com.hazelcast.core.HazelcastException) SocketChannelWrapper(com.hazelcast.internal.networking.SocketChannelWrapper) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) Socket(java.net.Socket) TimeoutException(java.util.concurrent.TimeoutException) HazelcastException(com.hazelcast.core.HazelcastException) IOException(java.io.IOException) AuthenticationException(com.hazelcast.client.AuthenticationException)

Example 88 with SocketChannel

use of java.nio.channels.SocketChannel in project hazelcast by hazelcast.

the class SocketAcceptorThread method acceptSocket.

private void acceptSocket() {
    SocketChannelWrapper socketChannelWrapper = null;
    try {
        final SocketChannel socketChannel = serverSocketChannel.accept();
        if (socketChannel != null) {
            socketChannelWrapper = connectionManager.wrapSocketChannel(socketChannel, false);
        }
    } catch (Exception e) {
        exceptionCount.inc();
        if (e instanceof ClosedChannelException && !connectionManager.isLive()) {
            // ClosedChannelException
            // or AsynchronousCloseException
            // or ClosedByInterruptException
            logger.finest("Terminating socket acceptor thread...", e);
        } else {
            logger.severe("Unexpected error while accepting connection! " + e.getClass().getName() + ": " + e.getMessage());
            try {
                serverSocketChannel.close();
            } catch (Exception ex) {
                logger.finest("Closing server socket failed", ex);
            }
            ioService.onFatalError(e);
        }
    }
    if (socketChannelWrapper != null) {
        final SocketChannelWrapper socketChannel = socketChannelWrapper;
        logger.info("Accepting socket connection from " + socketChannel.socket().getRemoteSocketAddress());
        if (connectionManager.isSocketInterceptorEnabled()) {
            configureAndAssignSocket(socketChannel);
        } else {
            ioService.executeAsync(new Runnable() {

                @Override
                public void run() {
                    configureAndAssignSocket(socketChannel);
                }
            });
        }
    }
}
Also used : ServerSocketChannel(java.nio.channels.ServerSocketChannel) SocketChannel(java.nio.channels.SocketChannel) ClosedChannelException(java.nio.channels.ClosedChannelException) SocketChannelWrapper(com.hazelcast.internal.networking.SocketChannelWrapper) ClosedChannelException(java.nio.channels.ClosedChannelException) IOException(java.io.IOException)

Example 89 with SocketChannel

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

the class H2ONode method getTCPSocket.

ByteChannel getTCPSocket() throws IOException {
    // Under lock, claim an existing open socket if possible
    synchronized (this) {
        // Limit myself to the number of open sockets from node-to-node
        while (_socksAvail == 0) try {
            wait(1000);
        } catch (InterruptedException ignored) {
        }
        // Claim an open socket
        ByteChannel sock = _socks[--_socksAvail];
        if (sock != null) {
            // Return existing socket!
            if (sock.isOpen())
                return sock;
            // Else it's an already-closed socket, lower open TCP count
            assert TCPS.get() > 0;
            TCPS.decrementAndGet();
        }
    }
    // Must make a fresh socket
    SocketChannel sock2 = SocketChannel.open();
    sock2.socket().setReuseAddress(true);
    sock2.socket().setSendBufferSize(AutoBuffer.BBP_BIG._size);
    boolean res = sock2.connect(_key);
    assert res && !sock2.isConnectionPending() && sock2.isBlocking() && sock2.isConnected() && sock2.isOpen();
    ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
    bb.put((byte) 2);
    bb.putChar((char) H2O.H2O_PORT);
    bb.put((byte) 0xef);
    bb.flip();
    ByteChannel wrappedSocket = _socketFactory.clientChannel(sock2, _key.getHostName(), _key.getPort());
    while (bb.hasRemaining()) {
        wrappedSocket.write(bb);
    }
    // Cluster-wide counting
    TCPS.incrementAndGet();
    return wrappedSocket;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ByteChannel(java.nio.channels.ByteChannel) ByteBuffer(java.nio.ByteBuffer)

Example 90 with SocketChannel

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

the class H2ONode method openChan.

/**
   * Returns a new connection of type {@code tcpType}, the type can be either
   *   TCPReceiverThread.TCP_SMALL, TCPReceiverThread.TCP_BIG or
   *   TCPReceiverThread.TCP_EXTERNAL.
   *
   * If socket channel factory is set, the communication will considered to be secured - this depends on the
   * configuration of the {@link SocketChannelFactory}. In case of the factory is null, the communication won't be secured.
   * @return new socket channel
   */
public static ByteChannel openChan(byte tcpType, SocketChannelFactory socketFactory, InetAddress originAddr, int originPort) throws IOException {
    // Must make a fresh socket
    SocketChannel sock = SocketChannel.open();
    sock.socket().setReuseAddress(true);
    sock.socket().setSendBufferSize(AutoBuffer.BBP_BIG._size);
    InetSocketAddress isa = new InetSocketAddress(originAddr, originPort);
    // Can toss IOEx, esp if other node is still booting up
    boolean res = sock.connect(isa);
    assert res : "Should be already connected, but connection is in non-blocking mode and the connection operation is in progress!";
    sock.configureBlocking(true);
    assert !sock.isConnectionPending() && sock.isBlocking() && sock.isConnected() && sock.isOpen();
    sock.socket().setTcpNoDelay(true);
    ByteBuffer bb = ByteBuffer.allocate(4).order(ByteOrder.nativeOrder());
    bb.put(tcpType).putChar((char) H2O.H2O_PORT).put((byte) 0xef).flip();
    ByteChannel wrappedSocket = socketFactory.clientChannel(sock, isa.getHostName(), isa.getPort());
    while (bb.hasRemaining()) {
        // Write out magic startup sequence
        wrappedSocket.write(bb);
    }
    return wrappedSocket;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ByteChannel(java.nio.channels.ByteChannel) ByteBuffer(java.nio.ByteBuffer)

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