项目地址:https://github.com/windwant/windwant-demo/tree/master/io-service

Server:

package org.windwant.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousServerSocketChannel;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.Charset;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadLocalRandom; /**
* AsynchronousServerSocketChannel
*/
public class AIOServer implements Runnable{ private int port = 8889;
private int threadSize = 10;
protected AsynchronousChannelGroup asynchronousChannelGroup; protected AsynchronousServerSocketChannel serverChannel; public AIOServer(int port, int threadSize) {
this.port = port;
this.threadSize = threadSize;
init();
} private void init(){
try {
asynchronousChannelGroup = AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 10);
serverChannel = AsynchronousServerSocketChannel.open(asynchronousChannelGroup);
serverChannel.bind(new InetSocketAddress(port));
System.out.println("listening on port: " + port);
} catch (IOException e) {
e.printStackTrace();
}
} public void run() {
try{
if(serverChannel == null) return;
serverChannel.accept(this, new CompletionHandler<AsynchronousSocketChannel, AIOServer>() {
final ByteBuffer echoBuffer = ByteBuffer.allocateDirect(1024); public void completed(AsynchronousSocketChannel result, AIOServer attachment) {
System.out.println("==============================================================");
System.out.println("server process begin ...");
try {
System.out.println("client host: " + result.getRemoteAddress());
echoBuffer.clear();
result.read(echoBuffer).get();
echoBuffer.flip();
System.out.println("received : " + Charset.defaultCharset().decode(echoBuffer)); int random = ThreadLocalRandom.current().nextInt(5);
printProcess(random);
System.out.println("server deal request execute: " + random + "s"); String msg = "server test msg-" + Math.random();
System.out.println("server send data: " + msg);
result.write(ByteBuffer.wrap(msg.getBytes()));
System.out.println("server process end ...");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
attachment.serverChannel.accept(attachment, this);// 监听新的请求,递归调用。
} } public void failed(Throwable exc, AIOServer attachment) {
System.out.println("received failed");
exc.printStackTrace();
attachment.serverChannel.accept(attachment, this);
}
});
System.in.read();
}catch (Exception e){
e.printStackTrace();
}
} private void printProcess(int s) throws InterruptedException {
String dot = "";
for (int i = 0; i < s; i++) {
Thread.sleep(1000);
dot += ".";
System.out.println(dot); }
} public static void main(String[] args) throws IOException {
new Thread(new AIOServer(8989, 19)).start();
}
}

Client:

package org.windwant.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler; /**
* AsynchronousSocketChannel
*/
public class AIOClient implements Runnable{ private AsynchronousSocketChannel client;
private String host;
private int port;
public AIOClient(String host, int port) throws IOException {
this.client = AsynchronousSocketChannel.open();
this.host = host;
this.port = port;
} public static void main(String[] args) {
try {
new Thread(new AIOClient("127.0.0.1", 8989)).start();
System.in.read();
} catch (IOException e) {
e.printStackTrace();
} } public void run() {
client.connect(new InetSocketAddress(host, port), null, new CompletionHandler<Void, Object>() {
public void completed(Void result, Object attachment) {
String msg = "client test msg-" + Math.random();
client.write(ByteBuffer.wrap(msg.getBytes()));
System.out.println("client send data:" + msg);
} public void failed(Throwable exc, Object attachment) {
System.out.println("client send field...");
}
}); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
client.read(byteBuffer, this, new CompletionHandler<Integer, Object>() {
public void completed(Integer result, Object attachment) {
System.out.println(result);
System.out.println("client read data: " + new String(byteBuffer.array()));
} public void failed(Throwable exc, Object attachment) {
System.out.println("read faield");
}
});
}
}

2017-12-11  改造client: AsynchronousChannelGroup

package org.windwant.io.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousChannelGroup;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; /**
* AsynchronousSocketChannel
*/
public class AIOClient implements Runnable{ private AsynchronousChannelGroup group; //异步通道组 封装处理异步通道的网络IO操作
private String host;
private int port;
public AIOClient(String host, int port) {
this.host = host;
this.port = port;
initGroup();
} private void initGroup(){
if(group == null) {
try {
group = AsynchronousChannelGroup.withCachedThreadPool(Executors.newFixedThreadPool(5), 5); //使用固定线程池实例化组
} catch (IOException e) {
e.printStackTrace();
}
}
} private void send(){
try {
//异步流式socket通道 open方法创建 并绑定到组 group
final AsynchronousSocketChannel client = AsynchronousSocketChannel.open(group);
//连接
client.connect(new InetSocketAddress(host, port), null, new CompletionHandler<Void, Object>() {
public void completed(Void result, Object attachment) {
String msg = "client test msg-" + Math.random();
client.write(ByteBuffer.wrap(msg.getBytes()));
System.out.println(Thread.currentThread().getName() + " client send data:" + msg); final ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
client.read(byteBuffer, this, new CompletionHandler<Integer, Object>() {
public void completed(Integer result, Object attachment) {
System.out.println(Thread.currentThread().getName() + " client read data: " + new String(byteBuffer.array()));
try {
byteBuffer.clear();
if (client != null) client.close();
} catch (IOException e) {
e.printStackTrace();
}
} public void failed(Throwable exc, Object attachment) {
System.out.println("read faield");
}
});
} public void failed(Throwable exc, Object attachment) {
System.out.println("client send field...");
}
});
} catch (IOException e) {
e.printStackTrace();
}
} public void run() {
for (int i = 0; i < 100; i++) {
send();
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} @Override
protected void finalize() throws Throwable {
super.finalize();
group.awaitTermination(10000, TimeUnit.SECONDS);
} public static void main(String[] args) {
try {
new Thread(new AIOClient("127.0.0.1", 8989)).start();
System.in.read();
} catch (IOException e) {
e.printStackTrace();
} }
}

Java AIO 异步IO应用实例的更多相关文章

  1. Oracle 之 AIO (异步io)

    Linux 异步 I/O (AIO)是 Linux 内核中提供的一个增强的功能.它是Linux 2.6 版本内核的一个标准特性,AIO 背后的基本思想是允许进程发起很多 I/O 操作,而不用阻塞或等 ...

  2. 再谈一次关于Java中的 AIO(异步IO) 与 NIO(非阻塞IO)

    今天用ab进行压力测试时,无意发现的: Requests per second:    xxx [#/sec] (mean) ab -n 5000 -c 1000 http://www:8080/up ...

  3. Java网络编程和NIO详解5:Java 非阻塞 IO 和异步 IO

    Java网络编程和NIO详解5:Java 非阻塞 IO 和异步 IO Java 非阻塞 IO 和异步 IO 转自https://www.javadoop.com/post/nio-and-aio 本系 ...

  4. Java中的IO、NIO、File、BIO、AIO详解

    java中有几种类型的流?JDK为每种类型的流提供了一些抽象类以供继承,请说出他们分别是哪些类?         Java中的流分为两种,一种是字节流,另一种是字符流,分别由四个抽象类来表示(每种流包 ...

  5. Java 异步 IO

         新的异步功能的关键点,它们是Channel 类的一些子集,Channel 在处理IO操作的时候需要被切换成一个后台进程.一些需要访问较大,耗时的操作,或是其它的类似实例,可以考虑应用此功能. ...

  6. Java知识回顾 (9) 同步、异步IO

    一.基本概念 同步和异步: 同步和异步是针对应用程序和内核的交互而言的. 同步指的是用户进程触发IO 操作并等待或者轮询的去查看IO 操作是否就绪: 而异步是指用户进程触发IO 操作以后便开始做自己的 ...

  7. Oracle在Linux下使用异步IO(aio)配置

    1.首先用root用户安装以下必要的rpm包 # rpm -Uvh libaio-0.3.106-3.2.x86_64.rpm# rpm -Uvh libaio-devel-0.3.106-3.2.x ...

  8. Java网络编程 -- AIO异步网络编程

    AIO中的A即Asynchronous,AIO即异步IO.它是异步非阻塞的,客户端的I/O请求都是由OS先完成了再通知服务器应用去启动线程进行处理,一般我们的业务处理逻辑会变成一个回调函数,等待IO操 ...

  9. 异步IO与回调

    最好了解 Java NIO 中 Buffer.Channel 和 Selector 的基本操作,主要是一些接口操作,比较简单. 本文将介绍非阻塞 IO 和异步 IO,也就是大家耳熟能详的 NIO 和 ...

随机推荐

  1. jquery内容选择器(匹配内容为空的元素)

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/ ...

  2. jquery更改加载图片大小

    <script type="text/javascript"> $("img").css("width","80%&q ...

  3. Oracle数据库,内置函数小结

    1.聚合函数 count(字段) // 求非空行的数量 max(字段) // 获取最大值 sum(字段) //求和 avg(字段) // 平均值 min(字段) // 最小值 2.转换函数 to_da ...

  4. MVC-自定义HttpModule处理

    HttpModule是向实现类提供模块初始化和处置事件. 当一个HTTP请求到达HttpModule时,整个ASP.NET Framework系统还并没有对这个HTTP请求做任何处理,也就是说此时对于 ...

  5. java servlet上传centos服务器

    前面一篇随笔说了Centos上架设javaWeb运行环境的方法,这篇主要讲打包上传服务器. 一.数据库连接文件.propeties 为了数据库安全,mysql3306端口访问我做了ip访问限制,由于m ...

  6. No.020:Valid Parentheses

    问题: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the ...

  7. Ouibounce – 在用户离开你网站时显示模态弹窗

    Ouibounce 是一个微小的库,用于实现在用户离开你的网站的时候显示一个模式窗口.这个库可以帮助你增加着陆页的转换率. Ouibounce 会在当鼠标光标移动到接近(或通过)视口(viewport ...

  8. mysql A表部分记录复制到B表

    [不定时更新] 1.将一张表中部分记录的一或多个字段复制到另一张表中: 表A: 表B: 执行SQL: insert into B(f_userId,f_nickname) select f_telep ...

  9. HTML5 video 和 audio

    video 用于在HTML或者XHTML文档中嵌入视频内容 使用 video 元素至少要提供两种视频格式的文件:OGG 和 MP4 OGG:采用 Theora 视频格式和 Vorbis 音频解码器 ( ...

  10. JavaScript语言精粹学习笔记

    0.JavaScript的简单数据类型包括数字.字符创.布尔值(true/false).null和undefined值,其它值都是对象. 1.JavaScript只有一个数字类型,它在内部被表示为64 ...