Java Code Examples for java.nio.channels.ServerSocketChannel#configureBlocking()

The following examples show how to use java.nio.channels.ServerSocketChannel#configureBlocking() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: ChannelListener.java    From localization_nifi with Apache License 2.0 6 votes vote down vote up
/**
 * Adds a server socket channel for listening to connections.
 *
 * @param nicIPAddress - if null binds to wildcard address
 * @param port - port to bind to
 * @param receiveBufferSize - size of OS receive buffer to request. If less
 * than 0 then will not be set and OS default will win.
 * @throws IOException if unable to add socket
 */
public void addServerSocket(final InetAddress nicIPAddress, final int port, final int receiveBufferSize)
        throws IOException {
    final ServerSocketChannel ssChannel = ServerSocketChannel.open();
    ssChannel.configureBlocking(false);
    if (receiveBufferSize > 0) {
        ssChannel.setOption(StandardSocketOptions.SO_RCVBUF, receiveBufferSize);
        final int actualReceiveBufSize = ssChannel.getOption(StandardSocketOptions.SO_RCVBUF);
        if (actualReceiveBufSize < receiveBufferSize) {
            LOGGER.warn(this + " attempted to set TCP Receive Buffer Size to "
                    + receiveBufferSize + " bytes but could only set to " + actualReceiveBufSize
                    + "bytes. You may want to consider changing the Operating System's "
                    + "maximum receive buffer");
        }
    }
    ssChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    ssChannel.bind(new InetSocketAddress(nicIPAddress, port));
    ssChannel.register(serverSocketSelector, SelectionKey.OP_ACCEPT);
}
 
Example 2
Source File: SingleSocketTcpWriterTest.java    From kieker with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldConnectWithDefault() throws Exception {
	final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
	try {
		serverSocketChannel.bind(new InetSocketAddress(HOSTNAME, PORT));
		serverSocketChannel.configureBlocking(false);
		serverSocketChannel.accept(); // non-blocking accept

		final SingleSocketTcpWriter writer = new SingleSocketTcpWriter(this.configuration);
		try {
			writer.onStarting();
		} finally {
			writer.onTerminating();
		}
	} finally {
		serverSocketChannel.close();
	}

	Assert.assertTrue(true); // NOPMD (this test should not throw any exception)
}
 
Example 3
Source File: ConnectionHandler.java    From joal with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ServerSocketChannel bindToPort() throws IOException {
    // Bind to the first available port in the range
    ServerSocketChannel channel = null;

    for (int port = ConnectionHandler.PORT_RANGE_START; port <= ConnectionHandler.PORT_RANGE_END; port++) {
        final InetSocketAddress tryAddress = new InetSocketAddress(port);


        try {
            channel = ServerSocketChannel.open();
            channel.socket().bind(tryAddress);
            channel.configureBlocking(false);
            break;
        } catch (final IOException ioe) {
            // Ignore, try next port
            logger.warn("Could not bind to port {}: {}, trying next port...", tryAddress.getPort(), ioe.getMessage());
            try {
                if (channel != null) channel.close();
            } catch (final IOException ignored) {
            }
        }
    }

    if (channel == null || !channel.socket().isBound()) {
        throw new IOException("No available port for the BitTorrent client!");
    }
    return channel;
}
 
Example 4
Source File: EchoNIOServer.java    From JavaBase with MIT License 5 votes vote down vote up
public void start() throws IOException {
  Selector selector = Selector.open();
  //通过OPEN方法来打开一个未绑定的ServerSocketChannel 实例
  ServerSocketChannel server = ServerSocketChannel.open();
  //将该ServerSocketChannel绑定到指定ip
  server.bind(new InetSocketAddress(NIOServer.PORT));
  //设置是NIO 非阻塞模式
  server.configureBlocking(false);

  //将sever注册到指定Selector对象上
  server.register(selector, SelectionKey.OP_ACCEPT);

  while (!stop) {
    selector.select(2000);
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    Iterator<SelectionKey> it = selectedKeys.iterator();
    SelectionKey key;
    while (it.hasNext()) {
      key = it.next();
      it.remove();
      try {
        handleInput(selector, key);
      } catch (Exception e) {
        if (key != null) {
          key.cancel();
          if (key.channel() != null) {
            key.channel().close();
          }
        }
      }
    }
  }
}
 
Example 5
Source File: NioServerProcessor.java    From light-task-scheduler with Apache License 2.0 5 votes vote down vote up
private static ServerSocketChannel newSocket() {
    try {
        ServerSocketChannel ch = ServerSocketChannel.open();
        ch.configureBlocking(false);
        return ch;
    } catch (IOException e) {
        throw new NioException("Open a server socket error:" + e.getMessage(), e);
    }
}
 
Example 6
Source File: NIOConnector.java    From ServletContainer with GNU General Public License v3.0 5 votes vote down vote up
public NIOConnector init() {
    try {
        this.selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        ServerSocket serverSocket = serverSocketChannel.socket();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(80);
        serverSocket.bind(inetSocketAddress);
        serverSocketChannel.register(this.selector, SelectionKey.OP_ACCEPT);
    }catch(IOException e){
        e.printStackTrace();
    }
    return this;
}
 
Example 7
Source File: DownstreamServer.java    From nassau with Apache License 2.0 5 votes vote down vote up
public static DownstreamServer open(UpstreamFactory upstream,
        InetSocketAddress address) throws IOException {
    ServerSocketChannel serverChannel = ServerSocketChannel.open();

    serverChannel.bind(address);
    serverChannel.configureBlocking(false);

    return new DownstreamServer(upstream, serverChannel);
}
 
Example 8
Source File: Worker.java    From LightComm4J with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * open server socket channel
 * @param msg
 * message
 * @return
 * ServerSocketChannel
 */
public ServerSocketChannel openServerSocketChannelNonBlocking(String msg) {
	ServerSocketChannel serverSocketChannel;
	do {
		try {
			serverSocketChannel = ServerSocketChannel.open();
			serverSocketChannel.configureBlocking(false);
			return serverSocketChannel;
		} catch (IOException e) {
			this.logger.warning(msg + e.toString());
		}
	} while (true);
}
 
Example 9
Source File: NioServer.java    From Geisha with GNU General Public License v3.0 5 votes vote down vote up
private void start() throws Exception {
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.socket().bind(new InetSocketAddress(port));
    serverSocketChannel.configureBlocking(false);

    selector = Selector.open();
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
        selector.select(); // 此处的select方法是阻塞的
        // 对所有的key做一次遍历,由key本身判断此事件是否与自己有关
        selector.selectedKeys().forEach((this::handleKey));
    }
}
 
Example 10
Source File: EchoServerOld.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void initSelector() throws IOException {
    Selector socketSelector = SelectorProvider.provider().openSelector();

    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);

    InetSocketAddress isa = new InetSocketAddress(hostAddress, port);
    serverChannel.socket().bind(isa);
    serverChannel.register(socketSelector, SelectionKey.OP_ACCEPT);
    this.selector = socketSelector;
}
 
Example 11
Source File: AbstractSelectorTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * @tests AbstractSelector#register(Selector,int)
 */
public void test_register_LSelectorI() throws Exception {
    Selector acceptSelector = SelectorProvider.provider().openSelector();
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);

    assertFalse(ssc.isRegistered());
    SelectionKey acceptKey = ssc.register(acceptSelector,
            SelectionKey.OP_ACCEPT);
    assertTrue(ssc.isRegistered());
    assertNotNull(acceptKey);
    assertTrue(acceptSelector.keys().contains(acceptKey));
}
 
Example 12
Source File: NIOServer.java    From code with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    // 1、创建选择器
    Selector selector = Selector.open();
    // 2、将通道注册到选择器上
    ServerSocketChannel ssChannel = ServerSocketChannel.open();
    // 设置非阻塞
    ssChannel.configureBlocking(false);
    ssChannel.register(selector, SelectionKey.OP_ACCEPT);
    // 3、监听事件
    ServerSocket serverSocket = ssChannel.socket();
    serverSocket.bind(new InetSocketAddress("127.0.0.1", 8080));

    while (true) {
        selector.select();
        Set<SelectionKey> keys = selector.selectedKeys();
        Iterator<SelectionKey> keyIterator = keys.iterator();
        // 5、事件循环
        while (keyIterator.hasNext()) {
            SelectionKey key = keyIterator.next();
            // 4、获取到达的事件
            if (key.isAcceptable()) {
                ServerSocketChannel ssChannel1 = (ServerSocketChannel) key.channel();
                // 服务器会为每个新连接创建一个 SocketChannel
                SocketChannel socketChannel = ssChannel1.accept();
                socketChannel.configureBlocking(false);
                // 这个新连接主要用于从客户端读取数据
                socketChannel.register(selector, SelectionKey.OP_READ);
            } else if (key.isReadable()) {
                SocketChannel sChannel = (SocketChannel) key.channel();
                System.out.println(readDataFromSocketChannel(sChannel));
                sChannel.close();
            }
            keyIterator.remove();
        }

    }

}
 
Example 13
Source File: MultiThreadNIOEchoServer.java    From LearningOfThinkInJava with Apache License 2.0 4 votes vote down vote up
private void startServer() throws Exception{
        //声明一个selector
        selector= SelectorProvider.provider().openSelector();

        //声明一个server socket channel,而且是非阻塞的。
        ServerSocketChannel ssc=ServerSocketChannel.open();
        ssc.configureBlocking(false);

//        InetSocketAddress isa=new InetSocketAddress(InetAddress.getLocalHost(),8000);
        //声明服务器端的端口
        InetSocketAddress isa=new InetSocketAddress(8000);
        //服务器端的socket channel绑定在这个端口。
        ssc.socket().bind(isa);
        //把一个socketchannel注册到一个selector上,同时选择监听的事件,SelectionKey.OP_ACCEPT表示对selector如果
        //监听到注册在它上面的server socket channel准备去接受一个连接,或 有个错误挂起,selector将把OP_ACCEPT加到
        //key ready set 并把key加到selected-key set.
        SelectionKey acceptKey=ssc.register(selector,SelectionKey.OP_ACCEPT);

        for(;;){
            selector.select();
            Set readyKeys=selector.selectedKeys();
            Iterator i=readyKeys.iterator();
            long e=0;
            while (i.hasNext()){
                SelectionKey sk=(SelectionKey)i.next();
                i.remove();

                if(sk.isAcceptable()){
                    doAccept(sk);
                }else if(sk.isValid()&&sk.isReadable()){
                    if(!geym_time_stat.containsKey(((SocketChannel)sk.channel()).socket())){
                        geym_time_stat.put(((SocketChannel)sk.channel()).socket(),System.currentTimeMillis());
                        doRead(sk);
                    }
                }else if(sk.isValid()&&sk.isWritable()){
                    doWrite(sk);
                    e=System.currentTimeMillis();
                    long b=geym_time_stat.remove(((SocketChannel)sk.channel()).socket());
                    System.out.println("spend"+(e-b)+"ms");
                }
            }
        }
    }
 
Example 14
Source File: LotsOfCancels.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 15
Source File: LotsOfCancels.java    From dragonwell8_jdk with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 16
Source File: ServerSocketChannelReopenTest.java    From netcrusher-java with Apache License 2.0 4 votes vote down vote up
private void reopen(Selector selector) throws Exception {
    ServerSocketChannel channel = ServerSocketChannel.open();
    channel.configureBlocking(false);
    channel.setOption(StandardSocketOptions.SO_REUSEADDR, true);
    channel.bind(new InetSocketAddress("127.0.0.1", 17777));

    // --- if channel is not registered with selector the following close() method works fine
    SelectionKey selectionKey = channel.register(selector, SelectionKey.OP_ACCEPT);

    // --- trying to cancel the registration in selector - doesn't help
    // selectionKey.cancel();
    // selector.wakeup();

    // --- trying to configure the socket as blocking - doesn't help
    // selectionKey.cancel();
    // channel.configureBlocking(true);

    // --- trying to register the channel in other selector - doesn't help
    // selectionKey.cancel();
    // Selector nullSelector = Selector.open();
    // channel.register(nullSelector, 0);
    // nullSelector.close();

    // --- it helps!!!
    // selectionKey.cancel();
    // selector.selectNow();

    channel.close();

    // PROBLEM: after close() has returned I still see this port is listening
    //
    //     C:\Dev>netstat -nao | grep 17777
    //     TCP    127.0.0.1:17777        0.0.0.0:0              LISTENING       xxxx
    //
    // so on the next bind I get an exception: java.net.BindException: Address already in use: bind

    // --- it helps!!!
    selector.selectNow();

    // --- it helps!!! but I don't want to because there could multiple server sockets on the same selector
    // selector.close();

    // --- trying to shake-up the selector - doesn't help
    // selector.wakeup();

    // --- trying to wait some time - doesn't help
    // Thread.sleep(10000);
}
 
Example 17
Source File: ListenTCPRecord.java    From nifi with Apache License 2.0 4 votes vote down vote up
@OnScheduled
public void onScheduled(final ProcessContext context) throws IOException {
    this.port = context.getProperty(PORT).evaluateAttributeExpressions().asInteger();

    final int readTimeout = context.getProperty(READ_TIMEOUT).asTimePeriod(TimeUnit.MILLISECONDS).intValue();
    final int maxSocketBufferSize = context.getProperty(MAX_SOCKET_BUFFER_SIZE).asDataSize(DataUnit.B).intValue();
    final int maxConnections = context.getProperty(MAX_CONNECTIONS).asInteger();
    final RecordReaderFactory recordReaderFactory = context.getProperty(RECORD_READER).asControllerService(RecordReaderFactory.class);

    // if the Network Interface Property wasn't provided then a null InetAddress will indicate to bind to all interfaces
    final InetAddress nicAddress;
    final String nicAddressStr = context.getProperty(NETWORK_INTF_NAME).evaluateAttributeExpressions().getValue();
    if (!StringUtils.isEmpty(nicAddressStr)) {
        NetworkInterface netIF = NetworkInterface.getByName(nicAddressStr);
        nicAddress = netIF.getInetAddresses().nextElement();
    } else {
        nicAddress = null;
    }

    SSLContext sslContext = null;
    SslContextFactory.ClientAuth clientAuth = null;
    final SSLContextService sslContextService = context.getProperty(SSL_CONTEXT_SERVICE).asControllerService(SSLContextService.class);
    if (sslContextService != null) {
        final String clientAuthValue = context.getProperty(CLIENT_AUTH).getValue();
        sslContext = sslContextService.createSSLContext(SslContextFactory.ClientAuth.valueOf(clientAuthValue));
        clientAuth = SslContextFactory.ClientAuth.valueOf(clientAuthValue);
    }

    // create a ServerSocketChannel in non-blocking mode and bind to the given address and port
    final ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    serverSocketChannel.configureBlocking(false);
    serverSocketChannel.bind(new InetSocketAddress(nicAddress, port));

    this.dispatcher = new SocketChannelRecordReaderDispatcher(serverSocketChannel, sslContext, clientAuth, readTimeout,
            maxSocketBufferSize, maxConnections, recordReaderFactory, socketReaders, getLogger());

    // start a thread to run the dispatcher
    final Thread readerThread = new Thread(dispatcher);
    readerThread.setName(getClass().getName() + " [" + getIdentifier() + "]");
    readerThread.setDaemon(true);
    readerThread.start();
}
 
Example 18
Source File: LotsOfCancels.java    From openjdk-8 with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}
 
Example 19
Source File: NIOServer.java    From spring-boot-demo with MIT License 4 votes vote down vote up
private void startServer() throws IOException {
    // 获得selector及通道(socketChannel)
    this.selector = Selector.open();
    ServerSocketChannel serverChannel = ServerSocketChannel.open();
    serverChannel.configureBlocking(false);

    // 绑定地址及端口
    InetSocketAddress listenAddr = new InetSocketAddress(this.addr, this.port);
    serverChannel.socket().bind(listenAddr);
    serverChannel.register(this.selector, SelectionKey.OP_ACCEPT);

    log.info("NIOServer运行中...按下Ctrl-C停止服务");

    while (true) {
        log.info("服务器等待新的连接和selector选择…");
        this.selector.select();

        // 选择key工作
        Iterator keys = this.selector.selectedKeys().iterator();
        while (keys.hasNext()) {
            SelectionKey key = (SelectionKey) keys.next();

            // 防止出现重复的key,处理完需及时移除
            keys.remove();

            //无效直接跳过
            if (!key.isValid()) {
                continue;
            }
            if (key.isAcceptable()) {
                this.accept(key);
            } else if (key.isReadable()) {
                this.read(key);
            } else if (key.isWritable()) {
                this.write(key);
            } else if (key.isConnectable()) {
                this.connect(key);
            }
        }
    }
}
 
Example 20
Source File: LotsOfCancels.java    From openjdk-jdk8u with GNU General Public License v2.0 4 votes vote down vote up
static void runTest(int initCount, int massCount, int maxSelectTime)
        throws Exception {
    testStartTime = System.nanoTime();

    InetSocketAddress address = new InetSocketAddress("127.0.0.1", 7359);

    // Create server channel, add it to selector and run epoll_ctl.
    log("Setting up server");
    Selector serverSelector = Selector.open();
    ServerSocketChannel server = ServerSocketChannel.open();
    server.configureBlocking(false);
    server.socket().bind(address, 5000);
    server.register(serverSelector, SelectionKey.OP_ACCEPT);
    serverSelector.selectNow();

    log("Setting up client");
    ClientThread client = new ClientThread(address);
    client.start();
    Thread.sleep(100);

    // Set up initial set of client sockets.
    log("Starting initial client connections");
    client.connectClients(initCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all initial client sockets, add to selector and run
    // epoll_ctl.
    log("Accepting initial connections");
    List<SocketChannel> serverChannels1 =
        acceptAndAddAll(serverSelector, server, initCount);
    if (serverChannels1.size() != initCount) {
        throw new Exception("Accepted " + serverChannels1.size() +
                            " instead of " + initCount);
    }
    serverSelector.selectNow();

    // Set up mass set of client sockets.
    log("Requesting mass client connections");
    client.connectClients(massCount);
    Thread.sleep(500);  // Wait for client connections to arrive

    // Accept all mass client sockets, add to selector and do NOT
    // run epoll_ctl.
    log("Accepting mass connections");
    List<SocketChannel> serverChannels2 =
        acceptAndAddAll(serverSelector, server, massCount);
    if (serverChannels2.size() != massCount) {
        throw new Exception("Accepted " + serverChannels2.size() +
                            " instead of " + massCount);
    }

    // Close initial set of sockets.
    log("Closing initial connections");
    closeAll(serverChannels1);

    // Now get the timing of select() call.
    log("Running the final select call");
    long startTime = System.nanoTime();
    serverSelector.selectNow();
    long duration = durationMillis(startTime);
    log("Init count = " + initCount +
        ", mass count = " + massCount +
        ", duration = " + duration + "ms");

    if (duration > maxSelectTime) {
        System.out.println
            ("\n\n\n\n\nFAILURE: The final selectNow() took " +
             duration + "ms " +
             "- seems like O(N^2) bug is still here\n\n");
        System.exit(1);
    }
}