项目地址: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. java.lang.NullPointerException org.apache.struts2.impl.StrutsActionProxy.getErrorMessage(StrutsActionProxy.java:69)

    采用SSH框架时出现了 java.lang.NullPointerException org.apache.struts2.impl.StrutsActionProxy.getErrorMessage ...

  2. MySQL Error Handling in Stored Procedures 2

    Summary: this tutorial shows you how to use MySQL handler to handle exceptions or errors encountered ...

  3. 从零开始学Python第0周:Python基本介绍(部分内容来源于网络)

    Python入门介绍 一,Python的基本介绍 (1)概要 Python是一种解释型,面向对象,动态数据类型的高级程序设计语言.常被广泛用于处理系统管理任务和web编程.现如今Python已经成为了 ...

  4. Gym 101102D---Rectangles(单调栈)

    题目链接 http://codeforces.com/gym/101102/problem/D problem  description Given an R×C grid with each cel ...

  5. ubuntu下golang环境配置

    安装go 可以到Golang中国下载go的安装包 解压安装包tar -C /usr/local -xzf <安装包> 添加环境变量`export PATH=$PATH:/usr/local ...

  6. SpringFramework的简介

    一.前言 Spring提供了一种轻量级的解决方案,用于建立"快装式企业应用".在此基础上,Spring还提供了包括声明式事务管理,RMI或Web Services远程访问业务逻辑, ...

  7. Node.js Web 开发框架大全《中间件篇》

    这篇文章与大家分享优秀的 Node.js 中间件模块.Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念.它的目标是帮助程序员构建高度可伸缩的应用程序,编写能够处 ...

  8. windows 端口 任务

  9. 【zepto学习笔记01】核心方法$()(补)

    前言 昨天学习了核心$(),有几个遗留问题,我们今天来看看吧 $.each 遍历数组/对象,将每条数据作为callback的上下文,并传入数据以及数据的索引进行处理,如果其中一条数据的处理结果明确返回 ...

  10. 【javascript激增的思考01】模块化编程

    前言 之前我做过一个web app(原来可以这么叫啦),在一个页面上有很多小窗口,每个小窗口都是独立的应用,比如: ① 我们一个小窗口数据来源是腾讯微博,需要形成腾讯微博app小窗口 ② 我们一个小窗 ...