Java AIO-异步通信

本文介绍了Java AIO(Asynchronous IO),它在JDK 1.7中引入,提供了异步非阻塞的通信方式。内容包括客户端和服务器端的实现,以及对应的处理器和日志配置。通过示例展示了AIO在服务端和客户端的运行结果。
摘要由CSDN通过智能技术生成

AIO(Asynchronous IO)即异步IO,特别需要说明的是,Java AIO需要JDK 1.7的支持

客户端

package com.test.client;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.StandardSocketOptions;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.log4j.Logger;

import com.test.handler.client.ConnectCompleteHandler;

public class Client {
	private Logger logger = Logger.getLogger(Client.class);

	private String host = "127.0.0.1";
	private int port = 9999;
	private int poolSize = 10;
	
	private static CountDownLatch serverStatus = new CountDownLatch(1);
	
	public Client() throws Exception {
		try {
			//池中的每个线程都在等待IO事件,当IO操作完成后,调用池中的线程处理CompleteHandler
			ExecutorService threadPool = Executors.newFixedThreadPool(poolSize);
			AsynchronousChannelGroup asyncChannelGroup 
					= AsynchronousChannelGroup.withThreadPool(threadPool);
			
			AsynchronousSocketChannel asyncSocketChannel = 
					AsynchronousSocketChannel.open(asyncChannelGroup);
			asyncSocketChannel.setOption(StandardSocketOptions.TCP_NODELAY, true);
			asyncSocketChannel.connect(new InetSocketAddress(host, port), 
					null, new ConnectCompleteHandler(asyncSocketChannel));
		} catch (IOException e) {
			logger.error("Cilent socket establish failed!");
			throw e;
		}
	}
	
	public static void main(String[] args) throws Exception {
		Client client = new Client();
		
		serverStatus.await();
	}
}

客户端处理器

package com.test.handler.client;

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

import org.apache.log4j.Logger;

//CompletionHandler<V,A>
//V-IO操作的结果,AsynchronousSocketChannel.open创建的异步连接,
//	asyncSocketChannel.connect实际没有IO操作,因此IO操作的结果为Void
//A-IO操作附件,
public class ConnectCompleteHandler 
		implements CompletionHandler<Void, Object> {
	private Logger logger = Logger.getLogger(ConnectCompleteHandler.class);
	
	AsynchronousSocketChannel asyncSocketChannel;
	
	public ConnectCompleteHandler(
			AsynchronousSocketChannel asyncSocketChannel){
		this.asyncSocketChannel = asyncSocketChannel;
	}
	
	@Override
	public void completed(Void result, Object attachment) {
		//使用asyncChannelGroup中保存的线程池中的线程进行处理
		logger.info("Deal thread of [ConnectCompleteHandler] : " 
				+ Thread.currentThread().getName());
	
		String request = "Hi, this is client!";
		logger.info("The request sent by client is : " + request);
		try {
			byte[] reqBytes = request.getBytes("utf-8");
			ByteBuffer writeByteBuffer = ByteBuffer.allocate(reqBytes.length);
			writeByteBu
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值