项目地址: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. ubuntu16.4下用jexus部署asp.net core rtm

    上篇文章介绍了下用vs发布部署到iis环境,今天说下ubuntu 下部署asp.net core,不需要安装.net core sdk,自带运行时方式部署,利用jexus服务器转发请求到asp.net ...

  2. 如何优雅地使用 Windows 10 ?

    身为一个伪电脑Geek,就算不懂电脑,也要把那些更不懂电脑的人给唬住. 1.入门级别: 当然就是让别人从视觉上感觉你的电脑不一般啦 第一步:桌面要干净,干净到什么程度呢,要像这样 当别人第一眼看到你的 ...

  3. jquery层级原则器(匹配前一个元素后的所有平辈元素)

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

  4. css background 背景图设置

  5. ActionSupport与action区别

    action是接口,只有一个execute方法需要实现.ActionSupport是action接口的一个实现类.这个类除了实现action接口还实现了Validateable(用于验证)等接口,开发 ...

  6. 项目总结笔记系列 wsTax KT Session1

     项目总结笔记 1.专有名词解释: SMO, Separate Management Office. UAT, User Accept Test. GSLB, Global Server Load B ...

  7. Scalaz(42)- Free :FreeAp-Applicative Style Programming Language

    我们在前面花了几期时间讨论Free Monad,那是因为FP既是Monadic programming,Free Monad是FP模式编程的主要方式.对我们来说,Free Monad代表着fp从学术探 ...

  8. 配置云服务器 FTP 服务

    自己配置的环境: OS: 阿里云 CentOS 6.5 >>Begin: 1. 登录到阿里云服务器(如何登录阿里云服务器), 在root权限下, 通过如下命令安装 vsftp [root@ ...

  9. ActiveMQ消息队列介绍

    ActiveMQ是一个开源兼容Java Message  Service  (JMS) 1.1面向消息的中件间. 来自Apache Software Foundation. ActiveMQ提供松耦合 ...

  10. 用div和css样式控制页面布局

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...