JAVA并发处理经验(四)并行模式与算法7:AIO网络编程

本文详细介绍了AIO(Asynchronous I/O)在异步网络编程中的应用,包括服务端和客户端的实现。通过使用异步通道,AIO允许在IO操作完成时接收通知,从而优化了业务逻辑的执行效率。

一、前言

我们已经学习了NIO是网络操作,提供了选择器selector阻塞操作,但是比较还是IO同步的。我等等IO准备好之后,得到通知,在进行IO操作。那么什么是AIO:Asynchronized;

那么AIo就是一个异步操作。---理解为:读完了再来通知我;我们业务逻辑变为回调函数,等等IO操作完成,由系统触发;

二、AIO

2.1服务端

package pattern.aio;

import pattern.nio.NioServer;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.ByteChannel;
import java.nio.channels.CompletionHandler;
import java.nio.channels.spi.AbstractInterruptibleChannel;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by ycy on 16/1/21.
 */
public class AIOServer {
//首先需要适用异步通道
    public final static int PORT=65500;
    private AsynchronousServerSocketChannel server;
    public AIOServer() throws IOException {
        server=AsynchronousServerSocketChannel.open().bind(new InetSocketAddress(PORT));
    }
public void start(){
    System.out.println("Server listen on" +PORT);
    //注册事件和事件完成过后的处理器
    server.accept(null, new CompletionHandler<AsynchronousSocketChannel, Object>() {
        public void completed(AsynchronousSocketChannel result, Object attachment) {
            final ByteBuffer buffer=ByteBuffer.allocate(1024);
            System.out.println(Thread.currentThread().getName());
            Future<Integer> writeResult=null;
            try{
                result.read(buffer).get(100, TimeUnit.SECONDS);
                buffer.flip();
                writeResult=result.write(buffer);
            }catch (InterruptedException|ExecutionException e){
                e.printStackTrace();
            }catch (TimeoutException e){
                e.printStackTrace();
            }finally {
                try {
                    server.accept(null,this);
                    writeResult.get();
                    result.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }

        public void failed(Throwable exc, Object attachment) {
            System.out.println("failed:"+exc);
        }


    });

}

    public static void main(String[] args) throws IOException, InterruptedException {
        new AIOServer().start();
        while (true){
            Thread.sleep(1000);
        }
    }


}

2.2 客户端


package pattern.aio;

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

/**
 * Created by ycy on 16/1/21.
 */
public class AIOClient {
    public static void main(String[] args) throws IOException, InterruptedException {
        final AsynchronousSocketChannel channel=AsynchronousSocketChannel.open();
        channel.connect(new InetSocketAddress("127.0.0.1", 65500), null, new CompletionHandler<Void, Object>() {
            @Override
            public void completed(Void result, Object attachment) {
                try {
                    final ByteBuffer buffer=ByteBuffer.allocate(1024);
                    channel.read(buffer, buffer, new CompletionHandler<Integer, ByteBuffer>() {
                        @Override
                        public void completed(Integer result, ByteBuffer attachment) {
                        buffer.flip();
                            System.out.println(new String(buffer.array()));
                            try{
                                channel.close();
                            }catch (IOException e){
                                e.printStackTrace();
                            }
                        }

                        @Override
                        public void failed(Throwable exc, ByteBuffer attachment) {

                        }
                    });
                }catch (Exception e){
                    e.printStackTrace();
                }

            }

            @Override
            public void failed(Throwable exc, Object attachment) {

            }
        });
        //主线程结束,这里等待 上时速处理全部完成
        Thread.sleep(1000);
    }
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值