非阻塞的示例

這篇博客講的很細服務器

https://www.jianshu.com/p/191041073919網絡

public class client2 {socket

public static void main(String[] args)throws Exception {
  client();
}

public static void client()throws Exception{

    //1建立網絡套接字
    SocketChannel socketChannel = SocketChannel.open
            (new InetSocketAddress("127.0.0.1",8989));

    //2切換爲非阻塞模式
    socketChannel.configureBlocking(false);

    //3創建緩衝區
    ByteBuffer buffer=ByteBuffer.allocate(1024);

    //4發送數據給服務器
	
    Scanner scanner =new Scanner(System.in);
    while (scanner.hasNext()) {
        String str = scanner.next();
        buffer.put((new Date().toString()+"\n"+str).getBytes());
        buffer.flip();
        socketChannel.write(buffer);
        buffer.clear();
    }


    //5關閉通道
    socketChannel.close();
}

}code

public class Server2 {server

public static void main(String[] args)throws Exception {
 server();
}

public static void server()throws Exception{事件

//1 打開服務器端套接字通訊
   ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();

   //2切換爲非阻塞模式
   serverSocketChannel.configureBlocking(false);

   //3綁定端口
   serverSocketChannel.bind(new InetSocketAddress(8989));

   //4獲取選擇器
   Selector selector =Selector.open();

   //5將通道註冊到選擇器中,並選擇進行哪一種操做,監聽接收事件
   serverSocketChannel.register(selector,SelectionKey.OP_ACCEPT);

   //6 輪詢選擇器上已經準備的事件
   while (selector.select()>0){
       //獲取當前選擇中全部註冊的選擇鍵
       Iterator<SelectionKey> iterator=selector.selectedKeys().iterator();

       //迭代器
       while (iterator.hasNext()){
           //獲取準備就緒的事件
           SelectionKey selectionKey=iterator.next();
           //判斷是哪一種事件的就緒
           if(selectionKey.isAcceptable()){
               //獲取客戶端的套接字通道
               SocketChannel socketChannel=serverSocketChannel.accept();
               //切換爲非阻塞模式
               socketChannel.configureBlocking(false);
               //注入到選擇器中,操做爲讀
               socketChannel.register(selector,SelectionKey.OP_READ);
       }else if(selectionKey.isReadable()){
               SocketChannel socketChannel=(SocketChannel) selectionKey.channel();
               //獲得一個緩衝區
               int len=0;
               ByteBuffer buffer=ByteBuffer.allocate(1024);
               while ((len=socketChannel.read(buffer))>0){
                   buffer.flip();
                   System.out.println(new String(buffer.array(),0,len));
                   buffer.clear();
               }
           }

           //取消選擇鍵
           iterator.remove();

       }
   }
}

}ip

相關文章
相關標籤/搜索