NIO非阻塞程式設計小案例

SpringCloud1發表於2018-05-14
 @Test
    public void client() throws  Exception{
        //1、獲取通道
        SocketChannel sChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
        //2、切換非阻塞
        sChannel.configureBlocking(false);
        //3、分配指定大小的緩衝區
        ByteBuffer buf = ByteBuffer.allocate(1024  );
        //4、傳送資料給伺服器
        buf.put(LocalDateTime.now().toString().getBytes());
        buf.flip();
        sChannel.write(buf);
        buf.clear();

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

    @Test
    public void server() throws IOException {
        //1獲取通道
        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        //2、切換非阻塞
        ssChannel.configureBlocking(false);
        //3/繫結連線
        ssChannel.bind(new InetSocketAddress(9898));
        //4 獲取選擇器
        Selector selector = Selector.open();
//        5、將通道註冊到選擇器,z指定監聽接收事件        ssChannel.register(selector, SelectionKey.OP_ACCEPT);
//        6. 輪詢式的獲取選擇器上已經準備好的事件
        while (selector.select()>0){
            //7、獲取當前選擇器中所有註冊的選擇鍵(已就緒的監聽事件            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                //8獲取準備就緒的事件
                SelectionKey sk = iterator.next();
                //9準備好了接收
                if(sk.isAcceptable()){
                    //10獲取客戶端連線
                    SocketChannel socketChannel = ssChannel.accept();
                    //11 切換非阻塞
                    socketChannel.configureBlocking(false);
                    //12註冊選擇器
                    socketChannel.register(selector,SelectionKey.OP_READ);
                }else if (sk.isReadable()){
                    //13獲得讀就緒通道
                    SocketChannel socketChannel = (SocketChannel) sk.channel();

                    //讀取資料
                    ByteBuffer buf = ByteBuffer.allocate(1024);

                    int len = 0;
                    while ((len= socketChannel.read(buf))>0){
                        buf.flip();
                        System.out.println(new String(buf.array(),0,len));
                        buf.clear();
                    }
                }
                iterator.remove();
            }
        }
    }

相關文章