4、java.nio、ServerSocketChannel Selector 非阻塞IO多路復(fù)用簡(jiǎn)單實(shí)用

客戶端參考:http://www.lxweimin.com/p/027af54275f3

public static void main(String[] args) throws Exception {
    // 打開一個(gè)多路io復(fù)用管理器
    Selector selector = Selector.open();
    // 打開一個(gè)tcp通道
    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
    // 設(shè)置非阻塞模式
    serverSocketChannel.configureBlocking(false);
    // 綁定監(jiān)聽本地ip端口
    serverSocketChannel.socket().bind(new InetSocketAddress("127.0.0.1", 8080));
    // 注冊(cè)連接事件
    serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
    while (true) {
      // 此方法會(huì)阻塞直到有io準(zhǔn)備好
      selector.select();
      // 獲取key迭代器
      Iterator<SelectionKey> selectionKeyIterator = selector.selectedKeys().iterator();
      // 如果有key
      while (selectionKeyIterator.hasNext()) {
        // 獲取一個(gè)key
        SelectionKey selectionKey = selectionKeyIterator.next();
        // 刪除獲取到的key以免重復(fù)獲取
        selectionKeyIterator.remove();
        // 如果是連接事件
        if (selectionKey.isAcceptable()) {
          // 獲取和客戶端連接的通道
          ServerSocketChannel sc = (ServerSocketChannel) selectionKey.channel();
          SocketChannel socketChannel = sc.accept();
          // 設(shè)置非阻塞模式
          socketChannel.configureBlocking(false);
          // 賦予讀寫通道的權(quán)限
          socketChannel.register(selector, SelectionKey.OP_READ | SelectionKey.OP_WRITE);
          // 發(fā)一條數(shù)據(jù)給客戶端
          socketChannel.write(ByteBuffer.wrap("我是服務(wù)端發(fā)來(lái)的".getBytes()));
          // 判斷到可讀的事件
        } else if (selectionKey.isReadable()) {
          // 得到此事件的socket通道
          SocketChannel sc = (SocketChannel) selectionKey.channel();
          ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
          int i = sc.read(byteBuffer);
          // -1表示客戶端已關(guān)閉并且沒(méi)有數(shù)據(jù)了
          //正確做法是while(sc.read(byteBuffer)>0)  一直接收,demo就簡(jiǎn)單寫了
          if (i != -1) {
            byte[] data = new byte[i];
            byteBuffer.flip();
            byteBuffer.get(data);
            System.out.println("服務(wù)器收到消息: " + new String(data));
          }
        }
      }
    }
  }
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。