Ejemplo n.º 1
0
  /**
   * 处理网络事件
   *
   * @param key
   * @throws IOException
   */
  private static void handle(SelectionKey key, Selector selector) throws IOException {
    if (key.isValid()) {
      if (key.isAcceptable()) {
        // 1、客户端请求连接事件(对应:serverChannel.register(selector, SelectionKey.OP_ACCEPT))
        ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
        // 2、接受并得到客户端连接
        SocketChannel channel = serverChannel.accept();
        // 3、设置为非阻塞模式
        channel.configureBlocking(false);
        // 4、得到客户端连接后,并不立即读取io,而是把客户端连接注册到多路复用器上,并监听读io事件
        channel.register(selector, SelectionKey.OP_READ);
      }

      if (key.isReadable()) {
        // 处理io读事件,(对应:channel.register(selector, SelectionKey.OP_READ);)
        SocketChannel channel = (SocketChannel) key.channel();
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        // 把客户端请求数据读到buffer中
        int readBytes = channel.read(buffer);
        if (readBytes > 0) {
          buffer.flip();
          byte[] bytes = new byte[buffer.remaining()];
          buffer.get(bytes);
          // 得到输入的字符串
          String inputStr = new String(bytes, CharsetUtil.UTF_8);
          System.out.println("收到的输入:" + inputStr);
          // 把了输入的字符串写回客户端
          if (!StringUtil.isNullOrEmpty(inputStr)) {
            byte[] resp = inputStr.getBytes(CharsetUtil.UTF_8);
            ByteBuffer wBuffer = ByteBuffer.allocate(resp.length);
            wBuffer.put(resp);
            wBuffer.flip();
            // 写回客户端
            channel.write(wBuffer);
          }
        }
      }
    }
  }