netty权威指南学习笔记一——NIO入门(4)AIO
NIO2.0引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。异步通道提供以下两种方式获取操作结果。
1、通过java.util.concurrent.Future 类来表示异步操作的结果;
2、在执行异步操作的时候传入一个java.io.channels。
ComplementHandler接口的实现类作为操作完成的回调。
NIO2.0的异步套接字通道是真正的异步非阻塞I/O,它不需要通过多路复用器(Selector)对注册的通道进行轮询操作即可实现异步读写,从而简化了NIO编程模型。
改造后的代码
server端代码:
package com.example.biodemo; import java.io.*;
import java.net.ServerSocket;
import java.net.Socket; public class TimeServer {
public static void main(String[] args) throws IOException {
int port = 8092;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
port = 8092;
}
}
AsyncTimeServerHandler timeServer = new AsyncTimeServerHandler(port);
new Thread(timeServer,"AsychronousTimeServerHandler").start(); // ===================改造代码为AIO将以下内容注释掉================================= // 创建多路复用线程类并初始化多路复用器,绑定端口等以及轮询注册功能
/* MultiplexerTimeServer timeServer = new MultiplexerTimeServer(port);
// 启动多路复用类线程负责轮询多路复用器Selector,IO数据处理等操作
new Thread(timeServer, "NIO-MultiplexerTimeSever-001").start();*/ // ===================以下内容注释掉================================= /* ServerSocket server = null;
try {
server = new ServerSocket(port);
System.out.println("the timeServer is start in port :" + port);
Socket socket = null;
// 引入线程池start
TimeServerHandlerExecutePool singleExecutor = new TimeServerHandlerExecutePool(50,10000);
while (true) {
socket = server.accept();
// 替换BIO中new Thread(new TimeServerHandler(socket)).start();为下一行代码
singleExecutor.execute(new TimeServerHandler(socket));
// 引入线程池end }
} finally {
if (server != null) {
System.out.println("the time server close");
server.close();
server = null;
}
}*/ }
}
异步时间服务处理器
package com.example.biodemo; 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 asynchronousServerSocketChannel;
public AsyncTimeServerHandler(int port) {
this.port=port;
try {
// 创建异步服务套接字通道
asynchronousServerSocketChannel = AsynchronousServerSocketChannel.open();
// 绑定监听端口
asynchronousServerSocketChannel.bind(new InetSocketAddress(port));
System.out.println("The time server is start in port"+port);
} catch (IOException e) {
e.printStackTrace();
}
} @Override
public void run() {
latch =new CountDownLatch(1);
// 接收客户端的连接
doAccept();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
} } private void doAccept() {
// AcceptCompletionHandler用于接收accept操作成功的通知消息
// accept(A attachment, CompletionHandler<AsynchronousSocketChannel,? super A> handler):接受连接,并为连接绑定一个CompletionHandler处理Socket连接
asynchronousServerSocketChannel.accept(this,new AcceptCompletionHandler());
}
}
AcceptCompletionHandle
package com.example.biodemo; import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousServerSocketChannel;
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) {
//再次让asynchronousServerSocketChannel对象调用accept方法是
//调用AsynchronousServerSocketChannel的accept方法后,如果有新的客户端接入,
// 系统将回调我们传入的CompletionHandler实例的completed方法,表示新客户端连接成功。
// 因为AsynchronousServerSocketChannel可以接受成千上万个客户端,所以需要继续调用它的accept方法,
// 接受其他客户端连接,最终形成一个环;每当一个客户端连接成功后,再异步接受新的客户端连接
attachment.asynchronousServerSocketChannel.accept(attachment,this);
// 据上,链路建立成功,服务端需要接受客户端新请求消息,
ByteBuffer buffer = ByteBuffer.allocate(1024);
// 调用read方法进行异步读操作
result.read(buffer,buffer,new ReadCompletionHandler(result));
} @Override
public void failed(Throwable exc, AsyncTimeServerHandler attachment) {
exc.printStackTrace();
attachment.latch.countDown();
} }
ReadCompletionHandler
package com.example.biodemo; 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) {
if(this.channel==null){
this.channel=channel;
}
} @Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] body = new byte[attachment.remaining()];
attachment.get(body);
try {
String req = new String(body,"utf-8");
System.out.println("The time server recerve order : "+req);
String currentTime = "QUERY TIME ORDER".equalsIgnoreCase(req)?new Date(System.currentTimeMillis()).toString():"BAD ORDER";
doWriter(currentTime);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} private void doWriter(String currentTime) {
if (currentTime != null && currentTime.trim().length() > 0) {
byte[] bytes = currentTime.getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
writeBuffer.put(bytes);
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) {
}
}
});
}
}
@Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
this.channel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
客户端的代码
package com.example.biodemo; import java.io.*;
import java.net.Socket; public class TimeClient {
public static void main(String[] args) {
int port = 8092;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException ne) {
port = 8092;
}
}
new Thread(new AsyncTimeClientHandler("127.0.0.1",port)).start(); // new Thread(new TimeClientHandles("127.0.0.1",port),"TimeClient-001").start();
/* 代码改造注释掉以下代码
Socket socket = null;
BufferedReader in = null;
PrintWriter out = null;
try {
socket = new Socket("127.0.0.1", port);
System.out.println(socket.getInputStream());
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
out = new PrintWriter(socket.getOutputStream(), true);
out.println("QUERY TIME ORDER");
System.out.println("send order 2 server succeed.");
String resp = in.readLine();
System.out.println("now is :" + resp);
} catch (IOException e1) { } finally {
if (out != null) {
out.close();
out = null;
} if (in != null) {
try {
in.close();
} catch (IOException e2) {
e2.printStackTrace();
}
in = null;
if (socket != null) {
try {
socket.close();
} catch (IOException e3) {
e3.printStackTrace();
} }
socket = null;
}
}*/
}
}
AsyncTimeClientHandler
package com.example.biodemo; 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 AsynchronousSocketChannel asynchronousSocketChannel;
private String host;
private int port;
private CountDownLatch latch; public AsyncTimeClientHandler(String host, int port) {
this.host = host == null ? "127.0.0.1" : host;
this.port = port;
try {
asynchronousSocketChannel = AsynchronousSocketChannel.open();
} catch (IOException e) {
e.printStackTrace();
}
} @Override
public void run() {
latch = new CountDownLatch(1);
asynchronousSocketChannel.connect(new InetSocketAddress(host, port), this, this);
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
asynchronousSocketChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
} @Override
public void completed(Void result, AsyncTimeClientHandler attachment) {
byte[] req = "QUERY TIME ORDER".getBytes();
ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
writeBuffer.put(req);
writeBuffer.flip();
asynchronousSocketChannel.write(writeBuffer, writeBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
if (attachment.hasRemaining()) {
asynchronousSocketChannel.write(attachment, attachment, this);
} else {
ByteBuffer readBuffer = ByteBuffer.allocate(1024);
asynchronousSocketChannel.read(readBuffer, readBuffer, new CompletionHandler<Integer, ByteBuffer>() {
@Override
public void completed(Integer result, ByteBuffer attachment) {
attachment.flip();
byte[] bytes = new byte[attachment.remaining()];
attachment.get(bytes);
String body = null;
try {
body = new String(bytes, "utf-8");
System.out.println(body);
System.out.println("Now is :" + body);
latch.countDown();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} } @Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
asynchronousSocketChannel.close();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
} @Override
public void failed(Throwable exc, ByteBuffer attachment) {
try {
asynchronousSocketChannel.close();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} @Override
public void failed(Throwable exc, AsyncTimeClientHandler attachment) {
exc.printStackTrace();
try {
asynchronousSocketChannel.close();
latch.countDown();
} catch (IOException e) {
e.printStackTrace();
}
}
}
学到这里我们对NIO编程已经有了一个感性认识。
netty权威指南学习笔记一——NIO入门(4)AIO的更多相关文章
- netty权威指南学习笔记一——NIO入门(1)BIO
公司的一些项目采用了netty框架,为了加速适应公司开发,本博主认真学习netty框架,前一段时间主要看了看书,发现编程这东西,不上手还是觉得差点什么,于是为了加深理解,深入学习,本博主还是决定多动手 ...
- netty权威指南学习笔记一——NIO入门(3)NIO
经过前面的铺垫,在这一节我们进入NIO编程,NIO弥补了原来同步阻塞IO的不足,他提供了高速的.面向块的I/O,NIO中加入的Buffer缓冲区,体现了与原I/O的一个重要区别.在面向流的I/O中,可 ...
- netty权威指南学习笔记一——NIO入门(2)伪异步IO
在上一节我们介绍了四种IO相关编程的各个特点,并通过代码进行复习了传统的网络编程代码,伪异步主要是引用了线程池,对BIO中服务端进行了相应的改造优化,线程池的引入,使得我们在应对大量客户端请求的时候不 ...
- netty权威指南学习笔记二——netty入门应用
经过了前面的NIO基础知识准备,我们已经对NIO有了较大了解,现在就进入netty的实际应用中来看看吧.重点体会整个过程. 按照权威指南写程序的过程中,发现一些问题:当我们在定义handler继承Ch ...
- netty权威指南学习笔记六——编解码技术之MessagePack
编解码技术主要应用在网络传输中,将对象比如BOJO进行编解码以利于网络中进行传输.平常我们也会将编解码说成是序列化/反序列化 定义:当进行远程跨进程服务调用时,需要把被传输的java对象编码为字节数组 ...
- netty权威指南学习笔记八——编解码技术之JBoss Marshalling
JBoss Marshalling 是一个java序列化包,对JDK默认的序列化框架进行了优化,但又保持跟java.io.Serializable接口的兼容,同时增加了一些可调参数和附加特性,这些参数 ...
- netty权威指南学习笔记五——分隔符和定长解码器的应用
TCP以流的方式进行数据传输,上层应用协议为了对消息进行区分,通常采用以下4中方式: 消息长度固定,累计读取到长度综合为定长LEN的报文后,就认为读取到了一个完整的消息,将计数器置位,重新开始读取下一 ...
- netty权威指南学习笔记三——TCP粘包/拆包之粘包现象
TCP是个流协议,流没有一定界限.TCP底层不了解业务,他会根据TCP缓冲区的实际情况进行包划分,在业务上,一个业务完整的包,可能会被TCP底层拆分为多个包进行发送,也可能多个小包组合成一个大的数据包 ...
- netty权威指南学习笔记七——编解码技术之GoogleProtobuf
首先我们来看一下protobuf的优点: 谷歌长期使用成熟度高: 跨语言支持多种语言如:C++,java,Python: 编码后消息更小,更利于存储传输: 编解码性能高: 支持不同协议版本的兼容性: ...
随机推荐
- 劫后余生--New Start
被搁置的计划 It was the best of times,it was the worst of times,it was the age of wisidom,it was the age o ...
- XML规范化(DTD)
无意义的XML 之前说过因为xml没有预设的标签,所以说你怎麽写他一般都不会报错. 所以需要对xml的书写格式进行一些限制,这就引入了DTD 下面的这个xml你可以给book添加各种属性还不会报错,但 ...
- Py西游攻关之基础数据类型(二)-列表
Py西游攻关之基础数据类型 - Yuan先生 https://www.cnblogs.com/yuanchenqi/articles/5782764.html 五 List(列表) OK,现在我们知 ...
- ubuntu 14 双击会自动删除文本
可能是ibus输入法引起,解决方法: Step1打开ibus首选项 $ibus-setup Step2 取消"Embed preedit text in application window ...
- python如何画三维图像?
python三维图像输出的代码如下所示:#画3D函数图像输出from mpl_toolkits.mplot3d import Axes3Dfrom matplotlib import cmimport ...
- Linux系统需要关闭的安全防护
1.关闭网络管理 我们一般在开发时都会将它关闭掉,因为它在做集群的时候,可能会劫持 systemctl status NetworkManager systemctl stop NetworkMana ...
- Iterator作用
前言 下面的内容是我从百度知道拷贝出来的,也就不在贴出链接了.我总结下就是迭代器在集合中使用,用户不需要关心具体集合实现的是如何遍历(不暴露细节),按照迭代器的方式遍历. 作用 Iterator模式是 ...
- node属性
认识node的方法 1.dom.nodeChildrens 用于获取dom下的子元素节点 2.dom.nodeType 用于获取dom节点的属性.共有12种属性,实用属性3种. 元素节点=>1 ...
- Regression 回归——多项式回归
回归是指拟合函数的模型.图像等.与分类不同,回归一般是在函数可微的情况下进行的.因为分类它就那么几类,如果把类别看做函数值的话,分类的函数值是离散的,而回归的函数值通常是连续且可微的.所以回归可以通过 ...
- 单元测试框架TestNg使用总结
工欲善其事,必先利其器 单元测试的重要性是不言而喻的.但如果没有好的单元测试工具,是无法激起开发人员的欲望. Testng便是利器之一.TestNG是基于Annotation的测试框架的先驱,他拥有通 ...