Search in sources :

Example 41 with ServerSocketChannel

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

the class CloseAfterConnect method main.

public static void main(String[] args) throws Exception {
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.socket().bind(new InetSocketAddress(0));
    InetAddress lh = InetAddress.getLocalHost();
    final SocketChannel sc = SocketChannel.open();
    final InetSocketAddress isa = new InetSocketAddress(lh, ssc.socket().getLocalPort());
    // establish connection in another thread
    Runnable connector = new Runnable() {

        public void run() {
            try {
                sc.connect(isa);
            } catch (IOException ioe) {
                ioe.printStackTrace();
            }
        }
    };
    Thread thr = new Thread(connector);
    thr.start();
    // terminate
    do {
        try {
            thr.join();
        } catch (InterruptedException x) {
        }
    } while (thr.isAlive());
    // check connection is established
    if (!sc.isConnected()) {
        throw new RuntimeException("SocketChannel not connected");
    }
    // close channel - this triggered the bug as it attempted to signal
    // a thread that no longer exists
    sc.close();
    // clean-up
    ssc.accept().close();
    ssc.close();
}
Also used : SocketChannel(java.nio.channels.SocketChannel) ServerSocketChannel(java.nio.channels.ServerSocketChannel) InetSocketAddress(java.net.InetSocketAddress) IOException(java.io.IOException) InetAddress(java.net.InetAddress) ServerSocketChannel(java.nio.channels.ServerSocketChannel)

Example 42 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 43 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 44 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 45 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)274 SocketChannel (java.nio.channels.SocketChannel)156 InetSocketAddress (java.net.InetSocketAddress)128 IOException (java.io.IOException)96 ByteBuffer (java.nio.ByteBuffer)53 SelectionKey (java.nio.channels.SelectionKey)41 ServerSocket (java.net.ServerSocket)37 Test (org.junit.Test)27 Socket (java.net.Socket)24 ClosedChannelException (java.nio.channels.ClosedChannelException)22 Selector (java.nio.channels.Selector)22 ClosedSelectorException (java.nio.channels.ClosedSelectorException)15 InetAddress (java.net.InetAddress)14 CancelledKeyException (java.nio.channels.CancelledKeyException)11 EOFException (java.io.EOFException)8 SocketException (java.net.SocketException)8 BindException (java.net.BindException)7 SocketAddress (java.net.SocketAddress)7 Test (org.junit.jupiter.api.Test)7 OutgoingPacket (com.twitter.heron.common.network.OutgoingPacket)6