`

Netty-入门AIO编程

 
阅读更多

在介绍Netty编程之前, 我们不得不限介绍一下Unix系统下的事件驱动IO模型;在JDK1.7之后出现的NIO2.0也引入了这个异步非阻塞通道,他不需要通过多路复用器对注册通道进行轮询操作即可实现异步读写,从而简化了NIO的编程模型;NIO2.0提供的异步的套接字通道是真正的异步I/O,在异步I/O操作的时候可以传递信号变量,当操作完成之后回调相关的方法。

 

异步I/O也被称作AIO。

 

 

下面介绍一下AIO程序,类图如下:

 

 

 

源码:

 

package com.techstar.aio;

public class AIOTimeServer {

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

 

package com.techstar.aio;

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

public class AsyncTimeServerHandler implements Runnable {

	
	private int port;
	
	CountDownLatch latch;
	AsynchronousServerSocketChannel asyncServerSocketChannel = null;
	
	
	
	public AsyncTimeServerHandler(int port) {
		this.port = port;
		try {
			this.asyncServerSocketChannel = AsynchronousServerSocketChannel.open();
			this.asyncServerSocketChannel.bind(new InetSocketAddress(this.port));
			System.out.println("The time server  is started! the port is " + this.port);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}



	@Override
	public void run() {
		
		latch = new CountDownLatch(1);
		this.doAccept();
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	private void doAccept() {
		this.asyncServerSocketChannel.accept(this, new AcceptCompletionHandler());
	}

}

 

package com.techstar.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.asyncServerSocketChannel.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();
	}

}

 

package com.techstar.aio;

import java.io.IOException;
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) {
		super();
		if (this.channel == null)
			this.channel = channel;
	}

	@Override
	public void completed(Integer result, ByteBuffer attachment) {

		try {
			attachment.flip();
			byte[] body = new byte[attachment.remaining()];
			attachment.get(body);
			String order = new String(body, "UTF-8");
			System.out.println("the client request Order = " + order );
			
			String currentTime = "QUERY TIME ORDER".equals(order)?new Date(System.currentTimeMillis()).toString() : "BAD ORDER";
			
			this.doWrite(currentTime);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

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

	private void doWrite(String response) {
		if (response != null && response.trim().length() > 0) {
			byte[] msg = response.getBytes();
			
			ByteBuffer writeBuffer = ByteBuffer.allocate(msg.length);
			writeBuffer.put(msg);
			writeBuffer.flip();
			channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {

				@Override
				public void completed(Integer result, ByteBuffer attachment) {
					if (attachment.hasRemaining()) {
						channel.write(attachment, attachment, this);
					}
				}

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

}

 

 

 

 

 

 

客户端代码

package com.techstar.aio;

public class AIOTimeClient {

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

 

package com.techstar.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 CompletionHandler<Void, AsyncTimeClientHandler>, Runnable {

	private int port;

	private String host;

	private AsynchronousSocketChannel channel;

	private CountDownLatch latch;

	public AsyncTimeClientHandler(int port, String host) {
		this.port = port;
		this.host = host;

		try {
			channel = AsynchronousSocketChannel.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		this.latch = new CountDownLatch(1);

		this.channel.connect(new InetSocketAddress(this.host, port), this, this);
		System.out.println("connect to the server。。。");
		try {
			this.latch.await();
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			this.channel.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Override
	public void completed(Void result, AsyncTimeClientHandler attachment) {
		byte[] order = "QUERY TIME ORDER".getBytes();
		this.doCompleted(order);
	}

	@Override
	public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
		try {
			this.channel.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	private void doCompleted(byte[] msg) {

		ByteBuffer writeBuffer = ByteBuffer.allocate(msg.length);
		writeBuffer.put(msg);
		writeBuffer.flip();
		channel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {

			@Override
			public void completed(Integer result, ByteBuffer attachment) {
				if (attachment.hasRemaining()) {
					try {
						System.out.println("发送消息指令:" + new String(msg, "UTF-8"));
					} catch (UnsupportedEncodingException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					channel.write(attachment, attachment, this);
				} else {
					ByteBuffer readBuffer = ByteBuffer.allocate(1024);
					channel.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {

						@Override
						public void completed(Integer result, ByteBuffer attachment) {
							attachment.flip();
							byte[] body = new byte[attachment.remaining()];
							
							attachment.get(body);
							String time;
							try {
								time = new String(body, "UTF-8");
								System.out.println("Now is:" + time);
								latch.countDown();
							} catch (UnsupportedEncodingException e) {
								e.printStackTrace();
							}
						}

						@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 {
					channel.close();
				} catch (IOException e) {
					e.printStackTrace();
				}

			}
		});
	}

}

 

  • 大小: 11.9 KB
  • 大小: 6.5 KB
分享到:
评论

相关推荐

    Java视频教程 Java游戏服务器端开发 Netty NIO AIO Mina视频教程

    二、java NIO,AIO编程视频教程 1、java NIO,AIO编程_01.flv 2、java NIO,AIO编程_02.flv 3、java NIO,AIO编程_03.flv 4、java NIO,AIO编程_04.flv 5、java NIO,AIO编程_05.flv 三、Java语言基础教程-Java NIO...

    Netty权威指南(含源码)

    总之,《Netty权威指南》是一本深度与广度并重的教程,不仅适合初学者入门,也适合有一定基础的开发者深入研究Netty的内部机制和最佳实践。通过学习本书,读者能够熟练掌握Netty,为构建高性能的网络应用奠定坚实...

    netty5.0架构剖析和源码解读

    业界主流的NIO框架如Netty、Mina等,它们封装了底层的NIO操作,提供了更高层次的网络编程抽象,简化了网络应用的开发。 2. NIO入门 Netty中的NIO实现主要基于java.nio包,NIO服务端和客户端的创建与传统IO模型有很...

    Netty5.0架构剖析和源码解读

    **解决方案探讨**:为了解决这些问题,人们开始探索更加高效的网络编程模型,如非阻塞I/O(NIO)、事件驱动I/O(AIO)等。其中,NIO因其高效性、灵活性等特点,成为了目前主流的网络编程方式之一。NIO允许单个线程...

    高并发编程实战1,2,3阶段

    #### 第一阶段:基础理论与实践入门 ##### 1. 高并发编程概述 - **定义**:高并发编程是指系统能够同时处理大量请求或任务的能力。 - **应用场景**:电商平台、社交网络、在线支付等需要处理海量用户访问的场景。 - ...

    Java高级架构必备知识点

    - **NIO基本概念及BIO、AIO的对比分析**:理解NIO、BIO和AIO之间的区别。 - **Netty实现IM聊天系统**:基于Netty开发即时通讯系统。 **7.21 分布式缓存技术-Redis** - **Redis的安装及数据类型分析**:掌握Redis的...

    Voovan开发手册

    Voovan作为一个专注于网络编程和异步通信的开源框架,不仅解决了传统框架中存在的问题,还大大降低了开发者的入门门槛。通过其丰富的功能和简单的API设计,开发者可以更加专注于业务逻辑的实现,而无需担心底层通信...

    你不可错过的Java学习资源清单

    4. Java网络编程与NIO:这部分内容讲解了Java的网络编程,包括Socket、IO模型(BIO、NIO、AIO)和相关的Linux网络编程知识。同时,介绍了Tomcat和Netty这两个NIO相关的高性能服务器。 5. JavaWeb技术世界:这个专栏...

Global site tag (gtag.js) - Google Analytics