Java Code Examples for java.nio.channels.Selector#selectedKeys()

The following examples show how to use java.nio.channels.Selector#selectedKeys() . 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: NIOAcceptor.java    From Mycat-NIO with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++acceptCount;
		try {
			selector.select(1000L);
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					if (key.isValid() && key.isAcceptable()) {
						accept();
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Throwable e) {
			LOGGER.warn(getName(), e);
		}
	}
}
 
Example 2
Source File: NIOConnector.java    From heisenberg with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final Selector selector = this.selector;
    for (;;) {
        ++connectCount;
        try {
            selector.select(1000L);
            connect(selector);
            Set<SelectionKey> keys = selector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid() && key.isConnectable()) {
                        finishConnect(key, att);
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Throwable e) {
            LOGGER.warn(name, e);
        }
    }
}
 
Example 3
Source File: NIOConnector.java    From tddl5 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final Selector selector = this.selector;
    for (;;) {
        ++connectCount;
        try {
            selector.select(1000L);
            connect(selector);
            Set<SelectionKey> keys = selector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid() && key.isConnectable()) {
                        finishConnect(key, att);
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Throwable e) {
            logger.warn(name, e);
        }
    }
}
 
Example 4
Source File: TCPNIOAcceptor.java    From Mycat-JCache with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void run() {
    final Selector selector = this.selector;
    for (; ; ) {
        try {
            selector.select(500L);
            Set<SelectionKey> keys = selector.selectedKeys();
            try {
                keys.forEach(this::handleKey);
            } finally {
                keys.clear();
            }
        } catch (Throwable e) {
            logger.warn(getName(), e);
        }
    }
}
 
Example 5
Source File: NIOAcceptor.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++acceptCount;
		try {
			selector.select( 1000L ); 
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					if (key.isValid() && key.isAcceptable()) {
						accept();							
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Throwable e) {
			LOGGER.warn(getName(), e);
		}
	}
}
 
Example 6
Source File: NIOConnector.java    From feeyo-redisproxy with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++connectCount;
		try {
			//查看有无连接就绪
			selector.select( 1000L );
			connect(selector);
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key: keys) {
					Object att = key.attachment();
					if (att != null && key.isValid() && key.isConnectable()) {
						finishConnect(key, att);
					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Exception e) {
			LOGGER.warn(name, e);
		}
	}
}
 
Example 7
Source File: EchoServer.java    From tutorials with MIT License 5 votes vote down vote up
public static void main(String[] args) throws IOException {
    Selector selector = Selector.open();
    ServerSocketChannel serverSocket = ServerSocketChannel.open();
    serverSocket.bind(new InetSocketAddress("localhost", 5454));
    serverSocket.configureBlocking(false);
    serverSocket.register(selector, SelectionKey.OP_ACCEPT);
    ByteBuffer buffer = ByteBuffer.allocate(256);

    while (true) {
        selector.select();
        Set<SelectionKey> selectedKeys = selector.selectedKeys();
        Iterator<SelectionKey> iter = selectedKeys.iterator();
        while (iter.hasNext()) {

            SelectionKey key = iter.next();

            if (key.isAcceptable()) {
                register(selector, serverSocket);
            }

            if (key.isReadable()) {
                answerWithEcho(buffer, key);
            }
            iter.remove();
        }
    }
}
 
Example 8
Source File: NIOReactor.java    From Mycat-JCache with GNU General Public License v2.0 5 votes vote down vote up
@Override
	public void run() {
		final Selector selector = this.selector;
		Set<SelectionKey> keys = null;
		int readys=0;
		for (;;) {
			try {
//				400/(readys+1)
				readys=selector.select(400);  //借鉴mycat-core
				if(readys==0) // 没有需要处理的事件时,处理新连接请求  注册 read 事件
				{
					handlerEvents(selector);  
					continue;
				}
				keys = selector.selectedKeys();
				for(SelectionKey key:keys)
				{
					Connection con = (Connection)key.attachment();
					logger.info("select-key-readyOps = {}, attachment = {}", key.readyOps(), con);
//					JcacheContext.getExecutor().execute(con);
					con.run();
				}
			} catch (Throwable e) {
				logger.warn(getName(), e);
			} finally {
				if (keys != null) {
					keys.clear();
				}
			}
			handlerEvents(selector); //处理完成事件后,处理新里连接请求 注册 read 事件
		}
	}
 
Example 9
Source File: NIOConnector.java    From Mycat-NIO with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
	final Selector selector = this.selector;
	for (;;) {
		++connectCount;
		try {
			selector.select(1000L);
			connect(selector);
			Set<SelectionKey> keys = selector.selectedKeys();
			try {
				for (SelectionKey key : keys) {
					Object att = key.attachment();
					if (att != null && key.isValid() && key.isConnectable()) {
						finishConnect(key, att);

					} else {
						key.cancel();
					}
				}
			} finally {
				keys.clear();
			}
		} catch (Throwable e) {
			LOGGER.warn(name, e);
		}
	}
}
 
Example 10
Source File: NIOReactor.java    From heisenberg with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final Selector selector = this.selector;
    for (;;) {
        ++reactCount;
        try {
            selector.select(1000L);
            register(selector);
            Set<SelectionKey> keys = selector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid()) {
                        int readyOps = key.readyOps();
                        if ((readyOps & SelectionKey.OP_READ) != 0) {
                            read((NIOConnection) att);
                        } else if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                            write((NIOConnection) att);
                        } else {
                            key.cancel();
                        }
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Throwable e) {
            LOGGER.warn(name, e);
        }
    }
}
 
Example 11
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 12
Source File: NIOReactor.java    From tddl5 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    final Selector selector = this.selector;
    for (;;) {
        ++reactCount;
        try {
            selector.select(1000L);
            register(selector);
            Set<SelectionKey> keys = selector.selectedKeys();
            try {
                for (SelectionKey key : keys) {
                    Object att = key.attachment();
                    if (att != null && key.isValid()) {
                        int readyOps = key.readyOps();
                        if ((readyOps & SelectionKey.OP_READ) != 0) {
                            read((NIOConnection) att);
                        } else if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                            write((NIOConnection) att);
                        } else {
                            key.cancel();
                        }
                    } else {
                        key.cancel();
                    }
                }
            } finally {
                keys.clear();
            }
        } catch (Throwable e) {
            logger.warn(name, e);
        }
    }
}
 
Example 13
Source File: AbstractNioWorker.java    From android-netty with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(Selector selector) throws IOException {
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    // check if the set is empty and if so just return to not create garbage by
    // creating a new Iterator every time even if there is nothing to process.
    // See https://github.com/netty/netty/issues/597
    if (selectedKeys.isEmpty()) {
        return;
    }
    for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) {
        SelectionKey k = i.next();
        i.remove();
        try {
            int readyOps = k.readyOps();
            if ((readyOps & SelectionKey.OP_READ) != 0 || readyOps == 0) {
                if (!read(k)) {
                    // Connection already closed - no need to handle write.
                    continue;
                }
            }
            if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                writeFromSelectorLoop(k);
            }
        } catch (CancelledKeyException e) {
            close(k);
        }

        if (cleanUpCancelledKeys()) {
            break; // break the loop to avoid ConcurrentModificationException
        }
    }
}
 
Example 14
Source File: AbstractNioWorker.java    From simple-netty-source with Apache License 2.0 5 votes vote down vote up
@Override
protected void process(Selector selector) throws IOException {
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    // check if the set is empty and if so just return to not create garbage by
    // creating a new Iterator every time even if there is nothing to process.
    // See https://github.com/netty/netty/issues/597
    if (selectedKeys.isEmpty()) {
        return;
    }
    for (Iterator<SelectionKey> i = selectedKeys.iterator(); i.hasNext();) {
        SelectionKey k = i.next();
        i.remove();
        try {
            int readyOps = k.readyOps();
            if ((readyOps & SelectionKey.OP_READ) != 0 || readyOps == 0) {
                if (!read(k)) {
                    // Connection already closed - no need to handle write.
                    continue;
                }
            }
            if ((readyOps & SelectionKey.OP_WRITE) != 0) {
                writeFromSelectorLoop(k);
            }
        } catch (CancelledKeyException e) {
            close(k);
        }

        if (cleanUpCancelledKeys()) {
            break; // break the loop to avoid ConcurrentModificationException
        }
    }
}
 
Example 15
Source File: Relay.java    From gnirehtet with Apache License 2.0 5 votes vote down vote up
public void run() throws IOException {
    Selector selector = Selector.open();

    // will register the socket on the selector
    TunnelServer tunnelServer = new TunnelServer(port, selector);

    Log.i(TAG, "Relay server started");

    long nextCleaningDeadline = System.currentTimeMillis() + UDPConnection.IDLE_TIMEOUT;
    while (true) {
        long timeout = Math.max(0, nextCleaningDeadline - System.currentTimeMillis());
        selector.select(timeout);
        Set<SelectionKey> selectedKeys = selector.selectedKeys();

        long now = System.currentTimeMillis();
        if (now >= nextCleaningDeadline || selectedKeys.isEmpty()) {
            tunnelServer.cleanUp();
            nextCleaningDeadline = now + CLEANING_INTERVAL;
        }

        for (SelectionKey selectedKey : selectedKeys) {
            SelectionHandler selectionHandler = (SelectionHandler) selectedKey.attachment();
            selectionHandler.onReady(selectedKey);
        }
        // by design, we handled everything
        selectedKeys.clear();
    }
}
 
Example 16
Source File: NIOServer.java    From JavaBase with MIT License 4 votes vote down vote up
private void start() throws Exception {
  Selector selector = Selector.open();

  //通过OPEN方法来打开一个未绑定的ServerSocketChannel 实例
  ServerSocketChannel server = ServerSocketChannel.open();

  //将该ServerSocketChannel绑定到指定 ip 端口
  server.bind(new InetSocketAddress(PORT));

  //设置是NIO 非阻塞模式
  server.configureBlocking(false);

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

  while (!stop) {
    // 因为只有在选择了至少一个通道后,才会返回该选择器的唤醒方法,或者当前线程中断,以先到者为准。否则一直阻塞
    selector.select();

    //依次处理selector上的每个已经准备好的管道
    Set<SelectionKey> selectedKeys = selector.selectedKeys();
    for (SelectionKey sk : selectedKeys) {
      //从selector上的已选择key集 中删除正在处理的连接请求
      selector.selectedKeys().remove(sk);

      // 连接 accept
      if (sk.isAcceptable()) {
        register(selector, server, sk);
      }
      // 连接建立
      else if (sk.isConnectable()) {
        System.out.println("close");
      }
      // 读就绪
      else if (sk.isReadable()) {
        readContent(selector, sk);
      }
      // 写就绪
      else if (sk.isWritable()) {

      }
    }
  }
}
 
Example 17
Source File: NioEchoServer.java    From JavaTutorial with Apache License 2.0 4 votes vote down vote up
/**
 * 启动服务器。
 * 
 * @param port 服务监听的端口
 * @param selectTimeout {@link Selector}检查通道就绪状态的超时时间(单位:毫秒)
 */
private static void startServer(int port, int selectTimeout) {
    ServerSocketChannel serverChannel = null;
    try {
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress(port));
        if (logger.isLoggable(Level.INFO)) {
            logger.info("NIO echo网络服务启动完毕,监听端口:" +port);
        }
        
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        
        while (true) {
            int selectNum = selector.select(selectTimeout);
            if (0 == selectNum) {
                continue;
            }
            
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) it.next();
                
                // 接受新的Socket连接
                if (selectionKey.isAcceptable()) {
                    acceptNew(selector, selectionKey);
                }
                
                // 读取并处理Socket的数据
                if (selectionKey.isReadable()) {
                    readData(selector, selectionKey);
                }
                
                it.remove();
            } // end of while iterator
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "处理网络连接出错", e);
    }
}
 
Example 18
Source File: Reactor.java    From JavaTutorial with Apache License 2.0 4 votes vote down vote up
/**
 * 启动服务。
 */
public void start() {
    ServerSocketChannel serverChannel = null;
    try {
        serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);
        ServerSocket serverSocket = serverChannel.socket();
        serverSocket.bind(new InetSocketAddress(_port));
        _isRun = true;
        if (logger.isLoggable(Level.INFO)) {
            logger.info("NIO echo网络服务启动完毕,监听端口:" +_port);
        }
        
        Selector selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT, new Acceptor(selector, serverChannel));
        
        while (_isRun) {
            int selectNum = selector.select(_selectTimeout);
            if (0 == selectNum) {
                continue;
            }
            
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> it = selectionKeys.iterator();
            while (it.hasNext()) {
                SelectionKey selectionKey = (SelectionKey) it.next();
                
                // 接受新的Socket连接
                if (selectionKey.isValid() && selectionKey.isAcceptable()) {
                     Acceptor acceptor = (Acceptor) selectionKey.attachment();
                     acceptor.accept();
                }
                
                // 读取并处理Socket的数据
                if (selectionKey.isValid() && selectionKey.isReadable()) {
                    Reader reader = (Reader) selectionKey.attachment();
                    reader.read();
                }
                
                // 移除已经处理过的Key
                it.remove();
            } // end of while iterator
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "处理网络连接出错", e);
    }
}
 
Example 19
Source File: SelectReceiveSendUdpPong.java    From aeron with Apache License 2.0 4 votes vote down vote up
private void run() throws IOException
{
    final InetSocketAddress sendAddress = new InetSocketAddress("localhost", Common.PONG_PORT);

    final ByteBuffer buffer = ByteBuffer.allocateDirect(Configuration.MTU_LENGTH_DEFAULT);

    final DatagramChannel receiveChannel = DatagramChannel.open();
    Common.init(receiveChannel);
    receiveChannel.bind(new InetSocketAddress("localhost", Common.PING_PORT));

    final DatagramChannel sendChannel = DatagramChannel.open();
    Common.init(sendChannel);

    final Selector selector = Selector.open();

    final IntSupplier handler =
        () ->
        {
            try
            {
                buffer.clear();
                receiveChannel.receive(buffer);

                final long receivedSequenceNumber = buffer.getLong(0);
                final long receivedTimestamp = buffer.getLong(SIZE_OF_LONG);

                buffer.clear();
                buffer.putLong(receivedSequenceNumber);
                buffer.putLong(receivedTimestamp);
                buffer.flip();

                sendChannel.send(buffer, sendAddress);
            }
            catch (final IOException ex)
            {
                ex.printStackTrace();
            }

            return 1;
        };

    receiveChannel.register(selector, OP_READ, handler);

    final AtomicBoolean running = new AtomicBoolean(true);
    SigInt.register(() -> running.set(false));

    while (true)
    {
        while (selector.selectNow() == 0)
        {
            if (!running.get())
            {
                return;
            }
        }

        final Set<SelectionKey> selectedKeys = selector.selectedKeys();
        final Iterator<SelectionKey> iter = selectedKeys.iterator();

        while (iter.hasNext())
        {
            final SelectionKey key = iter.next();
            if (key.isReadable())
            {
                ((IntSupplier)key.attachment()).getAsInt();
            }

            iter.remove();
        }
    }
}
 
Example 20
Source File: HAReceiveService.java    From database with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Blocking wait for a client connection.
 * 
 * @throws IOException
 *             if something goes wrong.
 */
protected void awaitAccept() throws IOException {

    // blocking wait for a client connection.
    final Selector serverSelector = Selector.open();
    try {

        final SelectionKey serverKey = server.register(serverSelector,
                SelectionKey.OP_ACCEPT);

        try {

            serverSelector.select(); // blocks

            final Set<SelectionKey> keys = serverSelector
                    .selectedKeys();

            final Iterator<SelectionKey> iter = keys.iterator();
            
            while (iter.hasNext()) {

                final SelectionKey key = (SelectionKey) iter.next();

                iter.remove();

                if (key != serverKey)
                    throw new AssertionError();

                break;
            }

        } finally {
            serverKey.cancel();
        }

    } finally {
        serverSelector.close();
    }

}