mina中的AIO

本文通过一个AIO(Asynchronous IO)的客户端和服务端案例,展示了Java NIO2.0如何实现真正的异步非阻塞IO操作。客户端通过AsynchronousSocketChannel发起连接并发送数据,服务端使用AsynchronousServerSocketChannel接收连接并处理请求,详细解释了异步IO的完成处理器和读写操作。

一 AIO

Nio2.0的异步套接字通道是真正的异步非阻塞io,Java nio 2.0的主要改进就是引入了异步IO(包括文件和网络)。

二 AIO案例

1.client

package com.cf.demo.aio2;

public class AioClient {

	public static void main(String[] args) {
		int port = 7080;
		new Thread(new AioClientAsyncHandler("127.0.0.1", port), "Client-001").start();;
	}
}

 

package com.cf.demo.aio2;


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 AioClientAsyncHandler implements CompletionHandler<Void, AioClientAsyncHandler>, Runnable {
	private String host;
	private int port;
	private CountDownLatch latch;
	private AsynchronousSocketChannel client;
	
	public AioClientAsyncHandler(String host, int port) {
		this.host = host;
		this.port = port;
		try {
			client = AsynchronousSocketChannel.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	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();
		}
	}

	public void completed(Void result, AioClientAsyncHandler attachment) {
		byte[] request = "jack".getBytes();
		ByteBuffer writeBuffer = ByteBuffer.allocate(request.length);
		writeBuffer.put(request);
		writeBuffer.flip();
		
		client.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {

			public void completed(Integer result, ByteBuffer buffer) {
				if (buffer.hasRemaining()) {
					client.write(buffer, buffer, this);
				} else {
					ByteBuffer readBuffer = ByteBuffer.allocate(1024);
					
					client.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {

						public void completed(Integer result, ByteBuffer buffer) {
							buffer.flip();
							byte[] bytes = new byte[buffer.remaining()];
							buffer.get(bytes);
							
							String body;
							try {
								body = new String(bytes, "UTF-8");
								System.out.println("client receive:" + body);
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						}

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

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

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

2.server

package com.cf.demo.aio2;

public class AioServer {

	public static void main(String[] args) {
		int port = 7080;
		//创建异步的处理类
		new Thread(new AioServerAsyncHandler(port), "Aio-Server-001").start();
	}
}
package com.cf.demo.aio2;

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

public class AioServerAsyncHandler implements Runnable {
	int port;
	CountDownLatch latch;
	AsynchronousServerSocketChannel asynchronousServerSocketChannel;
	
	public AioServerAsyncHandler(int port) {
		this.port = port;
		
		try {
			//异步服务端通道
			asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
			//绑定监听端口
			asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
			System.out.println("Server start:" + port);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void run() {
		//CountDownLatch对象运行在完成一组正在执行的操作之前,当前线程一直阻塞
		latch = new CountDownLatch(1);
		//接收客户端的连接
		doAccept();
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	public void doAccept() {
		//传递一个实现CompletionHandler<AsynchronousSocketChannel, ?>类型的handler实例来接收accept操作成功的通知消息
		asynchronousServerSocketChannel.accept(this, new AioServerAcceptHandler());
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值