NIO客户端与服务端

客户端

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();
            }
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值