AIO案例详解

本文深入探讨了AIO(Asynchronous I/O)在TimeServer和TimeClient中的应用,详细讲解了AsyncTimeServerHandler和AcceptCompletionHandler如何处理服务器端的异步连接,以及ReadCompletionHandler在客户端的读取操作中扮演的角色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

TimeServer :

package com.ck.prefix.aio;

public class TimeServer {

    public static void main(String[] args) {
        new Thread(new AsyncTimeServerHandler(8081)).start();
    }
}

 AsyncTimeServerHandler:

package com.ck.prefix.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.util.concurrent.CountDownLatch;

public class AsyncTimeServerHandler implements Runnable{

    public int port;

    public CountDownLatch latch;

   public AsynchronousServerSocketChannel asynchronousServerSocketChannel;

   public AsyncTimeServerHandler(int port){
       this.port = port;
       try {
           asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
           asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
           System.out.println("server init success");
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   @Override
    public void run() {
        latch = new CountDownLatch(1);
        doAccept();
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void doAccept(){
      asynchronousServerSocketChannel.accept(this, new AcceptCompletionHandler());
    }
}

AcceptCompletionHandler :

package com.ck.prefix.aio;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;

public class AcceptCompletionHandler implements CompletionHandler<AsynchronousSocketChannel,AsyncTimeServerHandler> {

    @Override
    public void completed(AsynchronousSocketChannel result, AsyncTimeServerHandler attachment) {
        attachment.asynchronousServerSocketChannel.accept(attachment,this);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        result.read(buffer,buffer,new ReadCompletionHandler(result));
    }
    @Override
    public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
        exc.printStackTrace();
        attachment.latch.countDown();
    }


}

ReadCompletionHandler :

package com.ck.prefix.aio;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.Date;

public class ReadCompletionHandler implements CompletionHandler<Integer,ByteBuffer> {

    private AsynchronousSocketChannel channel;

    public ReadCompletionHandler(AsynchronousSocketChannel channel){
        this.channel = channel;
    }

    @Override
    public void completed(Integer result, ByteBuffer attachment) {
        attachment.flip();
        byte [] bytes = new byte[attachment.remaining()];
        attachment.get(bytes);
        try {
            String body = new String(bytes,"UTF-8");
            if(body.equals("query time")){
                doWrite();
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public void doWrite(){
    final byte [] rep = new Date().toString().getBytes();
    final ByteBuffer buffer = ByteBuffer.allocate(rep.length);
    buffer.put(rep);
    buffer.flip();
    channel.write(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
        @Override
        public void completed(Integer result, ByteBuffer attachment) {
            //如果没有发送完成,继续发送
            if(attachment.hasRemaining()){
                channel.write(buffer, buffer, this);
            }
        }

        @Override
        public void failed(Throwable exc, ByteBuffer attachment) {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    });
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {
        try {
            this.channel.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

TimeClient :

package com.ck.prefix.aio;

public class TimeClient {
    public static void main(String[] args) {
        new Thread(new AsyncTimeClientHandler("127.0.0.1",8081)).start();
    }
}

AsyncTimeClientHandler:

package com.ck.prefix.aio;

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

public class AsyncTimeClientHandler implements Runnable,CompletionHandler<Void, AsyncTimeClientHandler> {

    private AsynchronousSocketChannel client;

    private String host;

    private int port;

    private CountDownLatch latch;

    public AsyncTimeClientHandler(String host, int port) {
     this.host = host;
     this.port = port;
        try {
            client = AsynchronousSocketChannel.open();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
     latch = new CountDownLatch(1);
     client.connect(new InetSocketAddress(host, port),this,this);
        try {
            latch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void completed(Void result, AsyncTimeClientHandler attachment) {
        byte [] req = "query time".getBytes();
        final ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
        writeBuffer.put(req);
        writeBuffer.flip();
        client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
            @Override
            public void completed(Integer result, ByteBuffer attachment) {
             if(attachment.hasRemaining()){
                 client.write(writeBuffer,writeBuffer,this);
             }else {
                 ByteBuffer readBuffer = ByteBuffer.allocate(1024);
                 client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
                     @Override
                     public void completed(Integer result, ByteBuffer buffer) {
                         buffer.flip();
                         byte [] bytes = new byte[buffer.remaining()];
                         buffer.get(bytes);
                         try {
                             String body  = new String(bytes,"UTF-8");
                             System.out.println("接受服务端的response =" + body);
                             latch.countDown();
                         } catch (UnsupportedEncodingException e) {
                             e.printStackTrace();
                         }

                     }

                     @Override
                     public void failed(Throwable exc, ByteBuffer attachment) {
                         try {
                             client.close();
                             latch.countDown();
                         } catch (IOException e) {
                             e.printStackTrace();
                         }
                     }
                 });
             }
            }

            @Override
            public void failed(Throwable exc, ByteBuffer attachment) {
                try {
                    client.close();
                    latch.countDown();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

    }

    @Override
    public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
        try {
            client.close();
            latch.countDown();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值