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的更多相关文章

  1. netty权威指南学习笔记一——NIO入门(1)BIO

    公司的一些项目采用了netty框架,为了加速适应公司开发,本博主认真学习netty框架,前一段时间主要看了看书,发现编程这东西,不上手还是觉得差点什么,于是为了加深理解,深入学习,本博主还是决定多动手 ...

  2. netty权威指南学习笔记一——NIO入门(3)NIO

    经过前面的铺垫,在这一节我们进入NIO编程,NIO弥补了原来同步阻塞IO的不足,他提供了高速的.面向块的I/O,NIO中加入的Buffer缓冲区,体现了与原I/O的一个重要区别.在面向流的I/O中,可 ...

  3. netty权威指南学习笔记一——NIO入门(2)伪异步IO

    在上一节我们介绍了四种IO相关编程的各个特点,并通过代码进行复习了传统的网络编程代码,伪异步主要是引用了线程池,对BIO中服务端进行了相应的改造优化,线程池的引入,使得我们在应对大量客户端请求的时候不 ...

  4. netty权威指南学习笔记二——netty入门应用

    经过了前面的NIO基础知识准备,我们已经对NIO有了较大了解,现在就进入netty的实际应用中来看看吧.重点体会整个过程. 按照权威指南写程序的过程中,发现一些问题:当我们在定义handler继承Ch ...

  5. netty权威指南学习笔记六——编解码技术之MessagePack

    编解码技术主要应用在网络传输中,将对象比如BOJO进行编解码以利于网络中进行传输.平常我们也会将编解码说成是序列化/反序列化 定义:当进行远程跨进程服务调用时,需要把被传输的java对象编码为字节数组 ...

  6. netty权威指南学习笔记八——编解码技术之JBoss Marshalling

    JBoss Marshalling 是一个java序列化包,对JDK默认的序列化框架进行了优化,但又保持跟java.io.Serializable接口的兼容,同时增加了一些可调参数和附加特性,这些参数 ...

  7. netty权威指南学习笔记五——分隔符和定长解码器的应用

    TCP以流的方式进行数据传输,上层应用协议为了对消息进行区分,通常采用以下4中方式: 消息长度固定,累计读取到长度综合为定长LEN的报文后,就认为读取到了一个完整的消息,将计数器置位,重新开始读取下一 ...

  8. netty权威指南学习笔记三——TCP粘包/拆包之粘包现象

    TCP是个流协议,流没有一定界限.TCP底层不了解业务,他会根据TCP缓冲区的实际情况进行包划分,在业务上,一个业务完整的包,可能会被TCP底层拆分为多个包进行发送,也可能多个小包组合成一个大的数据包 ...

  9. netty权威指南学习笔记七——编解码技术之GoogleProtobuf

    首先我们来看一下protobuf的优点: 谷歌长期使用成熟度高: 跨语言支持多种语言如:C++,java,Python: 编码后消息更小,更利于存储传输: 编解码性能高: 支持不同协议版本的兼容性: ...

随机推荐

  1. Codeforces 1300E. Water Balance

    给你一个数列,有一个操作,将一段数字变成其和除以个数,求字典序最小的那一个,分析知,求字典序最小,就是求一个不下降序列,但我们此时有可以更改数字的操作,已知已经不下降的序列不会因为操作而变的更小,只有 ...

  2. Java 使用 JDBC 连接数据库的代码整合[MySql、SqlServer、Oracle]-[经过设计模式改造](2020年寒假小目标01)

    日期:2020.01.08 博客期:121 星期三 今天对过去整个大二和大三上半学期用到的数据库的方法进行汇总,可以有效的使用.套用,每一个部分都有<软件设计模式>知识,上述代码满足了开闭 ...

  3. 查漏补缺之slice

    interviewer:说一说slice interviewee: 主要包括以下几点 slice and array slice的底层数据结构 length和capacity 切片的capacity的 ...

  4. python 爬虫原理

    简单来说互联网是由一个个站点和网络组成的大网,我们通过浏览器访问站点,站点把HTML.JS.CSS代码返回给浏览器,这些代码经过浏览器解析.渲染,将丰富多彩的网页呈现我们眼前: 一.爬虫是什么? 如果 ...

  5. mysql odbc 配置详解

    1.安装mysql 以及mysql odbc 要注意自己的版本 版本都要统一(32位 或者64位) 2.出现的error 1989 126错误代码 Error 1918. Error installi ...

  6. 科学计算库(BLAS,LAPACK,MKL,EIGEN)

    函数库接口标准:BLAS (Basic Linear Algebra Subprograms)和LAPACK (Linear Algebra PACKage) 1979年,Netlib首先用Fortr ...

  7. D. Number Of Permutations 符合条件的排列种类

    D. Number Of Permutations time limit per test 2 seconds memory limit per test 256 megabytes input st ...

  8. kafka-console-consumer接收不到flume推送过来的消息

    原因和解决方法:需要先启动kafka,再启动flume,两者启动有先后顺序.

  9. 启动storm任务时,异常提示

    启动storm任务时,异常提示: 14182 [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2000] WARN o.a.s.s.o.a.z.s.NIOServerCnx ...

  10. 使用input选择本地图片,并且实现预览功能

    1.使用input标签选择本地图片文件 用一个盒子来存放预览的图片 2.JS实现预览 首先添加一个input change事件,再用到 URL.createObjectURL() 方法 用来创建 UR ...