AIO基本编写

一、

public class Server {
    //线程池
    private ExecutorService executorService;
    //线程组
    private AsynchronousChannelGroup threadGroup;
    //服务器通道
    public AsynchronousServerSocketChannel assc;
    
    public Server(int port){
        try {
            //创建一个缓存池
            executorService = Executors.newCachedThreadPool();
            //创建线程组
            threadGroup = AsynchronousChannelGroup.withCachedThreadPool(executorService, 1);
            //创建服务器通道
            assc = AsynchronousServerSocketChannel.open(threadGroup);
            //进行绑定
            assc.bind(new InetSocketAddress(port));
            
            System.out.println("server start , port : " + port);
            //进行阻塞
            assc.accept(this, new ServerCompletionHandler());
            //一直阻塞 不让服务器停止
            Thread.sleep(Integer.MAX_VALUE);
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static void main(String[] args) {
        Server server = new Server(8765);
    }
    
}

二、

 1 public class ServerCompletionHandler implements CompletionHandler<AsynchronousSocketChannel, Server> {
 2 
 3     @Override
 4     public void completed(AsynchronousSocketChannel asc, Server attachment) {
 5         //当有下一个客户端接入的时候 直接调用Server的accept方法,这样反复执行下去,保证多个客户端都可以阻塞
 6         attachment.assc.accept(attachment, this);
 7         read(asc);
 8     }
 9 
10     private void read(final AsynchronousSocketChannel asc) {
11         //读取数据
12         ByteBuffer buf = ByteBuffer.allocate(1024);
13         asc.read(buf, buf, new CompletionHandler<Integer, ByteBuffer>() {
14             @Override
15             public void completed(Integer resultSize, ByteBuffer attachment) {
16                 //进行读取之后,重置标识位
17                 attachment.flip();
18                 //获得读取的字节数
19                 System.out.println("Server -> " + "收到客户端的数据长度为:" + resultSize);
20                 //获取读取的数据
21                 String resultData = new String(attachment.array()).trim();
22                 System.out.println("Server -> " + "收到客户端的数据信息为:" + resultData);
23                 String response = "服务器响应, 收到了客户端发来的数据: " + resultData;
24                 write(asc, response);
25             }
26             @Override
27             public void failed(Throwable exc, ByteBuffer attachment) {
28                 exc.printStackTrace();
29             }
30         });
31     }
32     
33     private void write(AsynchronousSocketChannel asc, String response) {
34         try {
35             ByteBuffer buf = ByteBuffer.allocate(1024);
36             buf.put(response.getBytes());
37             buf.flip();
38             asc.write(buf).get();
39         } catch (InterruptedException e) {
40             e.printStackTrace();
41         } catch (ExecutionException e) {
42             e.printStackTrace();
43         }
44     }
45     
46     @Override
47     public void failed(Throwable exc, Server attachment) {
48         exc.printStackTrace();
49     }
50 
51 }

三、

 1 public class Client implements Runnable{
 2 
 3     private AsynchronousSocketChannel asc ;
 4     
 5     public Client() throws Exception {
 6         asc = AsynchronousSocketChannel.open();
 7     }
 8     
 9     public void connect(){
10         asc.connect(new InetSocketAddress("127.0.0.1", 8765));
11     }
12     
13     public void write(String request){
14         try {
15             asc.write(ByteBuffer.wrap(request.getBytes())).get();
16             read();
17         } catch (Exception e) {
18             e.printStackTrace();
19         }
20     }
21 
22     private void read() {
23         ByteBuffer buf = ByteBuffer.allocate(1024);
24         try {
25             asc.read(buf).get();
26             buf.flip();
27             byte[] respByte = new byte[buf.remaining()];
28             buf.get(respByte);
29             System.out.println(new String(respByte,"utf-8").trim());
30         } catch (InterruptedException e) {
31             e.printStackTrace();
32         } catch (ExecutionException e) {
33             e.printStackTrace();
34         } catch (UnsupportedEncodingException e) {
35             e.printStackTrace();
36         }
37     }
38     
39     @Override
40     public void run() {
41         while(true){
42             
43         }
44     }
45     
46     public static void main(String[] args) throws Exception {
47         Client c1 = new Client();
48         c1.connect();
49         
50         Client c2 = new Client();
51         c2.connect();
52         
53         Client c3 = new Client();
54         c3.connect();
55         
56         new Thread(c1, "c1").start();
57         new Thread(c2, "c2").start();
58         new Thread(c3, "c3").start();
59         
60         Thread.sleep(1000);
61         
62         c1.write("c1 aaa");
63         c2.write("c2 bbbb");
64         c3.write("c3 ccccc");
65     }
66     
67 }

 

posted @ 2022-02-23 13:51  xujf  Views(26)  Comments(0Edit  收藏  举报