当前位置 博文首页 > lenkee的博客:NIO客户端与服务端

    lenkee的博客:NIO客户端与服务端

    作者:[db:作者] 时间:2021-08-31 19:20

    客户端

    class NioClient{
        public static void main(String args[]) throws IOException{
            System.out.println("客户端已经启动。。");
            // 1.创建socket通道
            SocketChannel schannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 8080));
            // 2.切换异步非阻塞
            schannel.configureBlocking(false);
            // 3.指定缓冲区大小
            ByteBuffer buff = ByteBuffer.allocate(1024);
            // 4.切换到读取模式
            buff.put(new Date().toString().getBytes());
            // 5.关闭通道
            schannel.close();
        }
    }

    ?服务端

    class Nioserver{
        public static void main(String args[]) throws IOException{
            System.out.println("服务端已经启动。。 ");
            // 1.创建服务通道
            ServerSocketChannel schannel = ServerSocketChannel.open();
            // 2.切换异步非阻塞
            schannel.configureBlocking(false);
            // 3.绑定连接
            schannel.bind(new InetSocketAddress(8080));
            // 4.获取选择器
            Selector selector = Selector.open();
            // 5.将通道注册到选择器中,并监听已经接收到的事件
            schannel.register(selector, SelectionKey.OP_ACCEPT);
            // 6.轮循获取 已经准备就绪的事件
            while(selector.select()>0){
                // 7.获取当前选择器
                Iterator<SelectionKey> it = selector.selectedKeys().iterator();
                while(it.hasNext()){
                    // 8.获取准备就绪事件
                    SelectionKey sk = it.next();
                    // 9.判断事件准备就绪
                    if(sk.isAcceptable()){
                        // 10.接收客户端连接
                        SocketChannel socketChannel = schannel.accept();
                        // 11.设置为阻塞模式
                        socketChannel.configureBlocking(false);
                        // 12.将通道注册到服务上
                        socketChannel.register(selector, SelectionKey.OP_READ);
                    }else if(sk.isReadable()){
                        // 13.获取当前选择 就绪状态 的通道
                        SocketChannel socketChannel = (SocketChannel) sk.channel();
                        // 14.读取数据
                        int len = 0;
                        ByteBuffer bf = ByteBuffer.allocate(1024);
                        while((len = socketChannel.read(bf))>0){
                            bf.flip();
                            System.out.println(new String(bf.array(),0,len));
                            bf.clear();
                        }
                    }
                    it.remove();
                }
            }
        }
    }

    ?

    cs
    下一篇:没有了