Java Code Examples for java.nio.channels.SelectionKey#isReadable()

The following examples show how to use java.nio.channels.SelectionKey#isReadable() . 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: Client.java    From SuitAgent with Apache License 2.0 6 votes vote down vote up
/**
 * 注册读写事件,轮训发生的事件
 * @throws IOException
 */
public void talk() throws IOException {
    socketChannel.register(selector,SelectionKey.OP_READ|SelectionKey.OP_WRITE|SelectionKey.OP_READ);
    while (selector.select() > 0){
        Set readyKeys = selector.selectedKeys();
        Iterator it = readyKeys.iterator();
        while (it.hasNext()){
            SelectionKey key = (SelectionKey) it.next();
            it.remove();
            if(key.isReadable()){
                receive(key);
            }
            if(shutdown){
                key.cancel();
                return;
            }
            if(key.isWritable()){
                send(key);
            }
        }
    }
}
 
Example 2
Source File: TestNonBlockingNIO2.java    From code with Apache License 2.0 6 votes vote down vote up
@Test
public void receive() throws IOException {
    DatagramChannel dc = DatagramChannel.open();
    dc.configureBlocking(false);
    dc.bind(new InetSocketAddress(9898));
    Selector selector = Selector.open();
    dc.register(selector, SelectionKey.OP_READ);
    while (selector.select() > 0) {
        Iterator<SelectionKey> it = selector.selectedKeys().iterator();
        while (it.hasNext()) {
            SelectionKey sk = it.next();

            if (sk.isReadable()) {
                ByteBuffer buf = ByteBuffer.allocate(1024);
                dc.receive(buf)
                ;
                buf.flip();
                System.out.println(new String(buf.array(), 0, buf.limit()));
                buf.clear();
            }
        }
        it.remove();
    }
}
 
Example 3
Source File: ActiveLookupProvider.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	if(key.isValid() && key.isWritable())
		write();
	if(key.isValid() && key.isReadable())
		read();
}
 
Example 4
Source File: EchoServerOld.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void loop() {
    while (true) {
        try {
            selector.select();
            Iterator<SelectionKey> selectedKeys = selector.selectedKeys().iterator();
            while (selectedKeys.hasNext()) {
                SelectionKey key = selectedKeys.next();
                selectedKeys.remove();

                if (!key.isValid()) {
                    continue;
                }

                // Check what event is available and deal with it
                if (key.isAcceptable()) {
                    accept(key);
                }
                else if (key.isReadable()) {
                    read(key);
                }
                else if (key.isWritable()) {
                    write(key);
                }
            }

        }
        catch (Exception e) {
            e.printStackTrace();
            System.exit(1);
        }
    }
}
 
Example 5
Source File: NioUdpClient.java    From dnsjava with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public void processReadyKey(SelectionKey key) {
  if (!key.isReadable()) {
    silentCloseChannel();
    f.completeExceptionally(new EOFException("channel not readable"));
    pendingTransactions.remove(this);
    return;
  }

  DatagramChannel channel = (DatagramChannel) key.channel();
  ByteBuffer buffer = ByteBuffer.allocate(max);
  int read;
  try {
    read = channel.read(buffer);
    if (read <= 0) {
      throw new EOFException();
    }
  } catch (IOException e) {
    silentCloseChannel();
    f.completeExceptionally(e);
    pendingTransactions.remove(this);
    return;
  }

  buffer.flip();
  byte[] data = new byte[read];
  System.arraycopy(buffer.array(), 0, data, 0, read);
  verboseLog(
      "UDP read",
      channel.socket().getLocalSocketAddress(),
      channel.socket().getRemoteSocketAddress(),
      data);
  silentCloseChannel();
  f.complete(data);
  pendingTransactions.remove(this);
}
 
Example 6
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 7
Source File: EchoServer.java    From netty.book.kor with MIT License 5 votes vote down vote up
private void startServer() throws Exception {
    selector = SelectorProvider.provider().openSelector();

    // Create non-blocking server socket.
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);

    // Bind the server socket to localhost.
    InetSocketAddress isa = new InetSocketAddress(InetAddress.getLocalHost(), 8888);
    ssc.socket().bind(isa);

    // Register the socket for select events.
    SelectionKey acceptKey = ssc.register(selector, SelectionKey.OP_ACCEPT);

    // Loop forever.
    for (;;) {
        selector.select();
        Set readyKeys = selector.selectedKeys();
        Iterator i = readyKeys.iterator();

        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            i.remove();

            if (sk.isAcceptable()) {
                doAccept(sk);
            }
            if (sk.isValid() && sk.isReadable()) {
                doRead(sk);
            }
            if (sk.isValid() && sk.isWritable()) {
                doWrite(sk);
            }
        }
    }
}
 
Example 8
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 9
Source File: AbstractPollingConnectionlessIoAcceptor.java    From neoscada with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private void processReadySessions( Set<SelectionKey> handles )
{
    Iterator<SelectionKey> iterator = handles.iterator();

    while ( iterator.hasNext() )
    {
        SelectionKey key = iterator.next();
        H handle = ( H ) key.channel();
        iterator.remove();

        try
        {
            if ( ( key != null ) && key.isValid() && key.isReadable() )
            {
                readHandle( handle );
            }

            if ( ( key != null ) && key.isValid() && key.isWritable() )
            {
                for ( IoSession session : getManagedSessions().values() )
                {
                    scheduleFlush( ( S ) session );
                }
            }
        }
        catch ( Throwable t )
        {
            ExceptionMonitor.getInstance().exceptionCaught( t );
        }
    }
}
 
Example 10
Source File: ReadWriteHandler.java    From incubator-gobblin with Apache License 2.0 5 votes vote down vote up
private void read()
    throws IOException {
  SelectionKey proxyKey = this.proxy.keyFor(this.selector);
  SelectionKey clientKey = this.client.keyFor(this.selector);

  SocketChannel readChannel = null;
  SocketChannel writeChannel = null;
  SelectionKey readKey = null;

  if (this.selector.selectedKeys().contains(proxyKey) && proxyKey.isReadable()) {
    readChannel = this.proxy;
    writeChannel = this.client;
    readKey = proxyKey;
  } else if (this.selector.selectedKeys().contains(clientKey) && clientKey.isReadable()) {
    readChannel = this.client;
    writeChannel = this.proxy;
    readKey = clientKey;
  }

  if (readKey != null) {

    int lastRead, totalRead = 0;

    while ((lastRead = readChannel.read(this.buffer)) > 0) {
      totalRead += lastRead;
    }

    LOG.debug("{} bytes read from {}", totalRead, readChannel == this.proxy ? "proxy":"client");

    if (totalRead > 0) {
      readKey.cancel();
      writeChannel.register(this.selector, SelectionKey.OP_WRITE, this);
      this.state = HandlerState.WRITING;
    }
    if (lastRead == -1) {
      readChannel.close();
    }
  }
}
 
Example 11
Source File: DatagramChannelReader.java    From localization_nifi with Apache License 2.0 5 votes vote down vote up
/**
 * Will receive UDP data from channel and won't receive anything unless the
 * given buffer has enough space for at least one full max udp packet.
 *
 * @param key selection key
 * @param buffer to fill
 * @return bytes read
 * @throws IOException if error filling buffer from channel
 */
@Override
protected int fillBuffer(final SelectionKey key, final ByteBuffer buffer) throws IOException {
    final DatagramChannel dChannel = (DatagramChannel) key.channel();
    final int initialBufferPosition = buffer.position();
    while (buffer.remaining() > MAX_UDP_PACKET_SIZE && key.isValid() && key.isReadable()) {
        if (dChannel.receive(buffer) == null || readSingleDatagram) {
            break;
        }
    }
    return buffer.position() - initialBufferPosition;
}
 
Example 12
Source File: Firehose.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	if(key.isValid() && key.isReadable())
		read();
	if(key.isValid() && key.isWritable())
		write();
}
 
Example 13
Source File: RPCServer.java    From mldht with Mozilla Public License 2.0 5 votes vote down vote up
@Override
public void selectionEvent(SelectionKey key) throws IOException {
	// schedule async writes first before spending thread time on reads
	if(key.isValid() && key.isWritable()) {
		writeState.set(WRITE_STATE_IDLE);
		connectionManager.interestOpsChanged(this);
		dh_table.getScheduler().execute(this::writeEvent);
	}
	if(key.isValid() && key.isReadable())
		readEvent();
		
}
 
Example 14
Source File: Server.java    From big-c with Apache License 2.0 5 votes vote down vote up
private synchronized void doRunLoop() {
  while (running) {
    SelectionKey key = null;
    try {
      // consume as many connections as currently queued to avoid
      // unbridled acceptance of connections that starves the select
      int size = pendingConnections.size();
      for (int i=size; i>0; i--) {
        Connection conn = pendingConnections.take();
        conn.channel.register(readSelector, SelectionKey.OP_READ, conn);
      }
      readSelector.select();

      Iterator<SelectionKey> iter = readSelector.selectedKeys().iterator();
      while (iter.hasNext()) {
        key = iter.next();
        iter.remove();
        if (key.isValid()) {
          if (key.isReadable()) {
            doRead(key);
          }
        }
        key = null;
      }
    } catch (InterruptedException e) {
      if (running) {                      // unexpected -- log it
        LOG.info(Thread.currentThread().getName() + " unexpectedly interrupted", e);
      }
    } catch (IOException ex) {
      LOG.error("Error in Reader", ex);
    }
  }
}
 
Example 15
Source File: Events.java    From parity with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    int numKeys;

    while (true) {
        try {
            numKeys = selector.select(TIMEOUT_MILLIS);
        } catch (IOException e) {
            break;
        }

        if (numKeys > 0) {
            Iterator<SelectionKey> keys = selector.selectedKeys().iterator();

            while (keys.hasNext()) {
                SelectionKey key = keys.next();

                if (key.isAcceptable())
                    accept();

                if (key.isReadable()) {
                    Object attachment = key.attachment();
                    if (attachment == marketData)
                        marketData.serve();
                    else if (attachment == marketReporting)
                        marketReporting.serve();
                    else
                        receive((Session)attachment);
                }

                keys.remove();
            }
        }

        keepAlive();

        cleanUp();
    }
}
 
Example 16
Source File: MultiThreadNIOEchoServer.java    From cs-summary-reflection with Apache License 2.0 4 votes vote down vote up
private void startServer() throws Exception {
    selector = SelectorProvider.provider().openSelector();
    // 创建非阻塞的服务器Socket通道
    ServerSocketChannel ssc = ServerSocketChannel.open();
    ssc.configureBlocking(false);

    // 绑定到指定的端口
    InetSocketAddress isa = new InetSocketAddress(8000);
    ssc.socket().bind(isa);
    // 注册到选择器,为监听,返回SelectionKey。无任何数据准备好则连接将阻塞
    ssc.register(selector, SelectionKey.OP_ACCEPT);

    // 轮询
    for (; ; ) {
        selector.select();
        Set<SelectionKey> readyKeys = selector.selectedKeys();
        Iterator<SelectionKey> i = readyKeys.iterator();
        long e = 0;
        while (i.hasNext()) {
            SelectionKey sk = (SelectionKey) i.next();
            // 连接操作处理
            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");
            }
            // 一定要取出这个SelectionKey,否则会重复处理相同的SelectionKey
            i.remove();
        }
    }
}
 
Example 17
Source File: SenderKeyHandler.java    From cacheonix-core with GNU Lesser General Public License v2.1 4 votes vote down vote up
public void handleKey(final SelectionKey key) throws InterruptedException {

      if (key.isConnectable()) {

         // Channel is ready to finish connection
         handleFinishConnect(key);

      } else if (key.isWritable()) { // NOPMD

         // Socket channel is ready for write
         handleWrite(key);

      } else if (key.isReadable()) { // NOPMD

         // Socket channel is ready for write
         handleRead(key);

      } else {
         //noinspection ObjectToString
         throw new IllegalArgumentException("Key is not supported: " + key);
      }
   }
 
Example 18
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 19
Source File: Main.java    From netty.book.kor with MIT License 4 votes vote down vote up
private void startEchoServer() {
    // open Selector and ServerSocketChannel by calling the open() method
    try (Selector selector = Selector.open(); ServerSocketChannel serverSocketChannel = ServerSocketChannel.open()) {

        // check that both of them were successfully opened
        if ((serverSocketChannel.isOpen()) && (selector.isOpen())) {

            // configure non-blocking mode
            serverSocketChannel.configureBlocking(false);

            // set some options
            serverSocketChannel.setOption(StandardSocketOptions.SO_RCVBUF, 256 * 1024);
            serverSocketChannel.setOption(StandardSocketOptions.SO_REUSEADDR, true);

            // bind the server socket channel to port
            serverSocketChannel.bind(new InetSocketAddress(8888));

            // register the current channel with the given selector
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);

            // display a waiting message while ... waiting!
            System.out.println("Waiting for connections ...");

            while (true) {
                // wait for incomming events
                selector.select();

                // there is something to process on selected keys
                Iterator keys = selector.selectedKeys().iterator();

                while (keys.hasNext()) {
                    SelectionKey key = (SelectionKey) keys.next();

                    // prevent the same key from coming up again
                    keys.remove();

                    if (!key.isValid()) {
                        continue;
                    }

                    if (key.isAcceptable()) {
                        acceptOP(key, selector);
                    }
                    else if (key.isReadable()) {
                        this.readOP(key);
                    }
                    else if (key.isWritable()) {
                        this.writeOP(key);
                    }
                }
            }

        }
        else {
            System.out.println("The server socket channel or selector cannot be opened!");
        }
    }
    catch (IOException ex) {
        System.err.println(ex);
    }
}
 
Example 20
Source File: NioSelectorLoop.java    From light-task-scheduler with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {

    while (running) {

        try {
            select();

            Set<SelectionKey> selectionKeys = selector.selectedKeys();

            if (selectionKeys.isEmpty()) {
                continue;
            }

            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()) {

                final SelectionKey key = iterator.next();
                iterator.remove();

                if (!key.isValid()) {
                    continue;
                }

                if (key.isAcceptable()) {
                    doAccept(key);
                }

                if (key.isConnectable()) {
                    doConnect(key);
                }

                if (key.isValid() && key.isReadable()) {
                    doRead(key);
                }

                if (key.isValid() && key.isWritable()) {
                    doWrite(key);
                }
            }

        } catch (Throwable t) {
            LOGGER.warn("Unexpected exception in the selector loop.", t);

            // 睡眠1S, 防止连续的异常导致cpu消耗
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ignore) {
            }
        }
    }
}