Search in sources :

Example 56 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project jdk8u_jdk by JetBrains.

the class LotsOfCancels method acceptAndAddAll.

static List<SocketChannel> acceptAndAddAll(Selector selector, ServerSocketChannel server, int expected) throws Exception {
    int retryCount = 0;
    int acceptCount = 0;
    List<SocketChannel> channels = new ArrayList<SocketChannel>();
    while (channels.size() < expected) {
        SocketChannel channel = server.accept();
        if (channel == null) {
            log("accept() returned null " + "after accepting " + acceptCount + " more connections");
            acceptCount = 0;
            if (retryCount < 10) {
                // See if more new sockets got stacked behind.
                retryCount++;
                Thread.sleep(500);
                continue;
            }
            break;
        }
        retryCount = 0;
        acceptCount++;
        channel.configureBlocking(false);
        channel.register(selector, SelectionKey.OP_READ);
        channels.add(channel);
    }
    // Cause an additional updateList entry per channel.
    for (SocketChannel channel : channels) {
        channel.register(selector, SelectionKey.OP_WRITE);
    }
    return channels;
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) ArrayList(java.util.ArrayList)

Example 57 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project jdk8u_jdk by JetBrains.

the class RacyDeregister method main.

public static void main(String[] args) throws Exception {
    InetAddress addr = InetAddress.getByName(null);
    ServerSocketChannel sc = ServerSocketChannel.open();
    sc.socket().bind(new InetSocketAddress(addr, 0));
    SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort()));
    SocketChannel accepted = sc.accept();
    accepted.configureBlocking(false);
    SocketChannel.open(new InetSocketAddress(addr, sc.socket().getLocalPort()));
    SocketChannel accepted2 = sc.accept();
    accepted2.configureBlocking(false);
    final Selector sel = Selector.open();
    SelectionKey key2 = accepted2.register(sel, SelectionKey.OP_READ);
    final SelectionKey[] key = new SelectionKey[] { accepted.register(sel, SelectionKey.OP_READ) };
    // thread that will be changing key[0].interestOps to OP_READ | OP_WRITE
    new Thread() {

        public void run() {
            try {
                for (int k = 0; k < 15; k++) {
                    for (int i = 0; i < 10000; i++) {
                        synchronized (notifyLock) {
                            synchronized (selectorLock) {
                                sel.wakeup();
                                key[0].interestOps(SelectionKey.OP_READ | SelectionKey.OP_WRITE);
                            }
                            notified = false;
                            long beginTime = System.currentTimeMillis();
                            while (true) {
                                notifyLock.wait(5000);
                                if (notified) {
                                    break;
                                }
                                long endTime = System.currentTimeMillis();
                                if (endTime - beginTime > 5000) {
                                    succTermination = false;
                                    // wake up main thread doing select()
                                    sel.wakeup();
                                    return;
                                }
                            }
                        }
                    }
                }
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            } catch (Exception e) {
                System.out.println(e);
                succTermination = true;
                // wake up main thread doing select()
                sel.wakeup();
            }
        }
    }.start();
    // main thread will be doing registering/deregistering with the sel
    while (true) {
        sel.select();
        if (Boolean.TRUE.equals(succTermination)) {
            System.out.println("Test passed");
            sel.close();
            sc.close();
            break;
        } else if (Boolean.FALSE.equals(succTermination)) {
            System.out.println("Failed to pass the test");
            sel.close();
            sc.close();
            throw new RuntimeException("Failed to pass the test");
        }
        synchronized (selectorLock) {
        }
        if (sel.selectedKeys().contains(key[0]) && key[0].isWritable()) {
            synchronized (notifyLock) {
                notified = true;
                notifyLock.notify();
                key[0].cancel();
                sel.selectNow();
                key2 = accepted2.register(sel, SelectionKey.OP_READ);
                key[0] = accepted.register(sel, SelectionKey.OP_READ);
            }
        }
        key2.cancel();
        sel.selectedKeys().clear();
    }
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) SelectionKey(java.nio.channels.SelectionKey) InetSocketAddress(java.net.InetSocketAddress) InetAddress(java.net.InetAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel) Selector(java.nio.channels.Selector)

Example 58 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project java-design-patterns by iluwatar.

the class NioServerSocketChannel method bind.

/**
 * Binds TCP socket on the provided <code>port</code>.
 *
 * @throws IOException if any I/O error occurs.
 */
@Override
public void bind() throws IOException {
    ((ServerSocketChannel) getJavaChannel()).socket().bind(new InetSocketAddress(InetAddress.getLocalHost(), port));
    ((ServerSocketChannel) getJavaChannel()).configureBlocking(false);
    LOGGER.info("Bound TCP socket at port: {}", port);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 59 with ServerSocketChannel

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

the class TCPConduit method createServerSocket.

/**
   * creates the server sockets. This can be used to recreate the socket using this.port and
   * this.bindAddress, which must be set before invoking this method.
   */
private void createServerSocket() {
    int p = this.port;
    int b = BACKLOG;
    InetAddress bindAddress = this.address;
    try {
        if (this.useNIO) {
            if (p <= 0) {
                socket = socketCreator.createServerSocketUsingPortRange(bindAddress, b, isBindAddress, this.useNIO, 0, tcpPortRange);
            } else {
                ServerSocketChannel channel = ServerSocketChannel.open();
                socket = channel.socket();
                InetSocketAddress inetSocketAddress = new InetSocketAddress(isBindAddress ? bindAddress : null, p);
                socket.bind(inetSocketAddress, b);
            }
            if (useNIO) {
                try {
                    // set these buffers early so that large buffers will be allocated
                    // on accepted sockets (see java.net.ServerSocket.setReceiverBufferSize javadocs)
                    socket.setReceiveBufferSize(tcpBufferSize);
                    int newSize = socket.getReceiveBufferSize();
                    if (newSize != tcpBufferSize) {
                        logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_0_IS_1_INSTEAD_OF_THE_REQUESTED_2, new Object[] { "Listener receiverBufferSize", Integer.valueOf(newSize), Integer.valueOf(tcpBufferSize) }));
                    }
                } catch (SocketException ex) {
                    logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_FAILED_TO_SET_LISTENER_RECEIVERBUFFERSIZE_TO__0, tcpBufferSize));
                }
            }
            channel = socket.getChannel();
        } else {
            try {
                if (p <= 0) {
                    socket = socketCreator.createServerSocketUsingPortRange(bindAddress, b, isBindAddress, this.useNIO, this.tcpBufferSize, tcpPortRange);
                } else {
                    socket = socketCreator.createServerSocket(p, b, isBindAddress ? bindAddress : null, this.tcpBufferSize);
                }
                int newSize = socket.getReceiveBufferSize();
                if (newSize != this.tcpBufferSize) {
                    logger.info(LocalizedMessage.create(LocalizedStrings.TCPConduit_0_IS_1_INSTEAD_OF_THE_REQUESTED_2, new Object[] { "Listener receiverBufferSize", Integer.valueOf(newSize), Integer.valueOf(this.tcpBufferSize) }));
                }
            } catch (SocketException ex) {
                logger.warn(LocalizedMessage.create(LocalizedStrings.TCPConduit_FAILED_TO_SET_LISTENER_RECEIVERBUFFERSIZE_TO__0, this.tcpBufferSize));
            }
        }
        port = socket.getLocalPort();
    } catch (IOException io) {
        throw new ConnectionException(LocalizedStrings.TCPConduit_EXCEPTION_CREATING_SERVERSOCKET.toLocalizedString(new Object[] { Integer.valueOf(p), bindAddress }), io);
    }
}
Also used : SocketException(java.net.SocketException) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) InetAddress(java.net.InetAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 60 with ServerSocketChannel

use of java.nio.channels.ServerSocketChannel in project suite by stupidsing.

the class NioDispatcherImpl method listen.

/**
 * Waits for incoming connections.
 *
 * @return event for switching off the server.
 */
@Override
public Closeable listen(int port) throws IOException {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);
    ssc.socket().bind(new InetSocketAddress(port));
    ssc.register(selector, SelectionKey.OP_ACCEPT);
    wakeUpSelector();
    return () -> Object_.closeQuietly(ssc);
}
Also used : InetSocketAddress(java.net.InetSocketAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

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