网络编程之AIO(异步非阻塞模型)

服务端

单线程模型

package com.yangmin.study.io.aio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

/**
 * @author yangmin
 * @version 1.0
 * @description: Aio的服务端
 * @date 2022/4/19 19:19
 */
public class Server {

    public static void main(String[] args) throws Exception {
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open()
                .bind(new InetSocketAddress(9999));

        /**
         * 异步操作,监听请求。处理请求和异常处理
         */
        serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            /**
             *
             * @param client 当前接受的客户端的连接会话,与客户端的通信都需要通过该连接会话进行。
             * @param attachment
             */
            @Override
            public void completed(AsynchronousSocketChannel client, Object attachment) {
                System.out.println(Thread.currentThread());
                //监听下一个请求
                serverSocketChannel.accept(null, this);
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    /**
                     *
                     * @param result 读取数据的指针,-1表示读取完成
                     * @param attachment 读取的数据放到缓冲区,一些请求的信息
                     */
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        System.out.println(Thread.currentThread());
                        //将缓冲区的指针归0,内容还存在
                        attachment.flip();
                        //打印请求头
                        System.out.println(new String(attachment.array(), 0, result));
                        client.write(ByteBuffer.wrap("hellowork".getBytes()));
                    }

                    /**
                     * 读取失败以后进行的一些操作
                     * @param exc
                     * @param attachment
                     */
                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        exc.printStackTrace();
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        Thread.sleep(10000);
    }
}

多线线程模型

package com.yangmin.study.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author yangmin
 * @version 1.0
 * @description: Aio服务端的多线程模式
 * @date 2022/4/19 20:24
 */
public class ServerGroup {
    public static void main(String[] args) throws IOException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(30);
        AsynchronousChannelGroup channelGroup = AsynchronousChannelGroup.withThreadPool(executorService);
        AsynchronousServerSocketChannel serverSocketChannel = AsynchronousServerSocketChannel.open(channelGroup).bind(new InetSocketAddress(8888));
        serverSocketChannel.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
            @Override
            public void completed(AsynchronousSocketChannel client, Object attachment) {
                System.out.println(Thread.currentThread());
                serverSocketChannel.accept(null, this);
                ByteBuffer buffer = ByteBuffer.allocate(1024);
                client.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                    @Override
                    public void completed(Integer result, ByteBuffer attachment) {
                        System.out.println(Thread.currentThread());
                        System.out.println(new String(attachment.array(), 0, result));
                        client.write(ByteBuffer.wrap("helloword2".getBytes()));
                    }

                    @Override
                    public void failed(Throwable exc, ByteBuffer attachment) {
                        exc.printStackTrace();
                    }
                });
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        Thread.sleep(10000);
    }
}

客户端

package com.yangmin.study.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.ExecutionException;

/**
 * @author yangmin
 * @version 1.0
 * @description: aio的客户端
 * @date 2022/4/19 19:57
 */
public class Client {

    public static void main(String[] args) throws IOException, InterruptedException {
        AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();
        socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999), null, new CompletionHandler<Void, Object>() {
            @Override
            public void completed(Void result, Object attachment) {
                System.out.println("成功连接到了服务器");
                //发送请求
                try {
                    //向服务器发送请求,并且通过get()方法阻塞等待服务器返回结果
                    socketChannel.write(ByteBuffer.wrap("From client:Hello i am client".getBytes())).get();
                    //解析服务器返回的结果
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    socketChannel.read(buffer).get();
                    System.out.println(new String(buffer.array()));
                } catch (InterruptedException | ExecutionException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void failed(Throwable exc, Object attachment) {
                exc.printStackTrace();
            }
        });
        Thread.sleep(10000);
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值