转载:http://m.blog.csdn.net/article/details?id=51512200
AIO异步非阻塞IO实例:客户端发送数学表达式,经过服务端接收计算后返回客户端。
1、服务端
包括,Server、ServerHandler、ServerWriteHandler、ServerReadHandler、AcceptHandler、Calculator
1.1 启动程序:
public class Server { private static int DEFAULT_PORT = 12345; private static AsyncServerHandler serverHandle; public volatile static long clientCount = 0; public static void start(){ start(DEFAULT_PORT); } public static synchronized void start(int port){ if(serverHandle!=null) return; serverHandle = new AsyncServerHandler(port); new Thread(serverHandle,"Server").start(); } public static void main(String[] args){ Server.start(); } }
1.2 AsyncServerHandler
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.AsynchronousServerSocketChannel; import java.util.concurrent.CountDownLatch; public class AsyncServerHandler implements Runnable{ public CountDownLatch latch; public AsynchronousServerSocketChannel channel; public AsyncServerHandler(int port) { try { //创建服务端通道 channel = AsynchronousServerSocketChannel.open(); //绑定端口 channel.bind(new InetSocketAddress(port)); System.out.println("服务器已启动,端口号:" + port); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { //CountDownLatch初始化 //它的作用:在完成一组正在执行的操作之前,允许当前的现场一直阻塞 //此处,让现场在此阻塞,防止服务端执行完成后退出 //也可以使用while(true)+sleep //生成环境就不需要担心这个问题,以为服务端是不会退出的 latch = new CountDownLatch(1); //用于接收客户端的连接 channel.accept(this,new AcceptHandler()); try { latch.await(); } catch (InterruptedException e) { e.printStackTrace(); } } }
1.3 AcceptHandler
import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; //作为handler接收客户端连接 public class AcceptHandler implements CompletionHandler<AsynchronousSocketChannel, AsyncServerHandler>{ @Override public void completed(AsynchronousSocketChannel channel, AsyncServerHandler serverHandler) { //继续接受其他客户端的请求 Server.clientCount++; System.out.println("连接的客户端数:" + Server.clientCount); serverHandler.channel.accept(serverHandler, this); //创建新的Buffer ByteBuffer buffer = ByteBuffer.allocate(1024); //异步读 第三个参数为接收消息回调的业务Handler channel.read(buffer, buffer, new ServerReadHandler(channel)); } @Override public void failed(Throwable exc, AsyncServerHandler serverHandler) { exc.printStackTrace(); serverHandler.latch.countDown(); } }
1.4 ServerReadHandler
import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; public class ServerReadHandler implements CompletionHandler<Integer, ByteBuffer> { //用于读取半包消息和发送应答 private AsynchronousSocketChannel channel; public ServerReadHandler(AsynchronousSocketChannel channel) { this.channel = channel; } //读取到消息后的处理 @Override public void completed(Integer result, ByteBuffer attachment) { //flip操作 attachment.flip(); //根据 byte[] message = new byte[attachment.remaining()]; attachment.get(message); try { String expression = new String(message, "UTF-8"); System.out.println("服务器收到消息: " + expression); String calrResult = null; try{ calrResult = Calculator.cal(expression).toString(); }catch(Exception e){ calrResult = "计算错误:" + e.getMessage(); } //向客户端发送消息 doWrite(calrResult); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } //发送消息 private void doWrite(String result) { byte[] bytes = result.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length); writeBuffer.put(bytes); writeBuffer.flip(); //异步写数据 参数与前面的read一样 channel.write(writeBuffer, writeBuffer,new ServerWriteHandler(channel)); } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { this.channel.close(); } catch (IOException e) { e.printStackTrace(); } } }
1.5 ServerWriteHandler
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; public class ServerWriteHandler implements CompletionHandler<Integer, ByteBuffer>{ private AsynchronousSocketChannel channel; public ServerWriteHandler(AsynchronousSocketChannel channel) { this.channel = channel; } @Override public void completed(Integer result, ByteBuffer buffer) { //如果没有发送完,就继续发送直到完成 if (buffer.hasRemaining()) channel.write(buffer, buffer, this); else{ //创建新的Buffer ByteBuffer readBuffer = ByteBuffer.allocate(1024); //异步读 第三个参数为接收消息回调的业务Handler channel.read(readBuffer, readBuffer, new ServerReadHandler(channel)); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { try { channel.close(); } catch (IOException e) { } } }
1.6 Calculator
import javax.script.ScriptEngine; import javax.script.ScriptEngineManager; import javax.script.ScriptException; public class Calculator { private final static ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript"); public static Object cal(String expression) throws ScriptException{ return jse.eval(expression); } }
2、客服端
包括 Client、ClientHandler、ClientWriteHandler、ClientReadHandler
2.1 启动器
import java.util.Scanner; public class Client { private static String DEFAULT_HOST = "127.0.0.1"; private static int DEFAULT_PORT = 12345; private static AsyncClientHandler clientHandle; public static void start(){ start(DEFAULT_HOST,DEFAULT_PORT); } public static synchronized void start(String ip,int port){ if(clientHandle!=null) return; clientHandle = new AsyncClientHandler(ip,port); new Thread(clientHandle,"Client").start(); } //向服务器发送消息 public static boolean sendMsg(String msg) throws Exception{ if(msg.equals("q")) return false; clientHandle.sendMsg(msg); return true; } @SuppressWarnings("resource") public static void main(String[] args) throws Exception{ Client.start(); System.out.println("请输入请求消息:"); Scanner scanner = new Scanner(System.in); while(Client.sendMsg(scanner.nextLine())); } }
2.2 AsyncClientHandler
import java.io.IOException; 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 AsyncClientHandler implements CompletionHandler<Void, AsyncClientHandler>, Runnable{ private AsynchronousSocketChannel clientChannel; private String host; private int port; private CountDownLatch latch; public AsyncClientHandler(String host, int port) { this.host = host; this.port = port; try { //创建异步的客户端通道 clientChannel = AsynchronousSocketChannel.open(); } catch (IOException e) { e.printStackTrace(); } } @Override public void run() { //创建CountDownLatch等待 latch = new CountDownLatch(1); //发起异步连接操作,回调参数就是这个类本身,如果连接成功会回调completed方法 clientChannel.connect(new InetSocketAddress(host, port), this, this); try { latch.await(); } catch (InterruptedException e1) { e1.printStackTrace(); } try { clientChannel.close(); } catch (IOException e) { e.printStackTrace(); } } //连接服务器成功 //意味着TCP三次握手完成 @Override public void completed(Void result, AsyncClientHandler attachment) { System.out.println("客户端成功连接到服务器..."); } //连接服务器失败 @Override public void failed(Throwable exc, AsyncClientHandler attachment) { System.err.println("连接服务器失败..."); exc.printStackTrace(); try { clientChannel.close(); latch.countDown(); } catch (IOException e) { e.printStackTrace(); } } //向服务器发送消息 public void sendMsg(String msg){ byte[] req = msg.getBytes(); ByteBuffer writeBuffer = ByteBuffer.allocate(req.length); writeBuffer.put(req); writeBuffer.flip(); //异步写 clientChannel.write(writeBuffer, writeBuffer,new ClientWriteHandler(clientChannel, latch)); } }
2.3 ClientWriteHandler
import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousSocketChannel; import java.nio.channels.CompletionHandler; import java.util.concurrent.CountDownLatch; public class ClientWriteHandler implements CompletionHandler<Integer, ByteBuffer>{ private AsynchronousSocketChannel clientChannel; private CountDownLatch latch; public ClientWriteHandler(AsynchronousSocketChannel clientChannel,CountDownLatch latch) { this.clientChannel = clientChannel; this.latch = latch; } @Override public void completed(Integer result, ByteBuffer buffer) { //完成全部数据的写入 if (buffer.hasRemaining()) { clientChannel.write(buffer, buffer, this); } else { //读取数据 ByteBuffer readBuffer = ByteBuffer.allocate(1024); clientChannel.read(readBuffer,readBuffer,new ClientReadHandler(clientChannel, latch)); } } @Override public void failed(Throwable exc, ByteBuffer attachment) { System.err.println("数据发送失败..."); try { clientChannel.close(); latch.countDown(); } catch (IOException e) { } } }
2.4 ClientReadHandler
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.concurrent.CountDownLatch; public class ClientReadHandler implements CompletionHandler<Integer, ByteBuffer> { private AsynchronousSocketChannel clientChannel; private CountDownLatch latch; public ClientReadHandler(AsynchronousSocketChannel clientChannel,CountDownLatch latch) { this.clientChannel = clientChannel; this.latch = latch; } @Override public void completed(Integer result,ByteBuffer buffer) { buffer.flip(); byte[] bytes = new byte[buffer.remaining()]; buffer.get(bytes); String body; try { body = new String(bytes,"UTF-8"); System.out.println("客户端收到结果:"+ body); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } @Override public void failed(Throwable exc,ByteBuffer attachment) { System.err.println("数据读取失败..."); try { clientChannel.close(); latch.countDown(); } catch (IOException e) { } } }
3、执行结果
服务器已启动,端口号:12345 请输入请求消息: 客户端成功连接到服务器... 连接的客户端数:1 123456+789+456 服务器收到消息: 123456+789+456 客户端收到结果:124701 9526*56 服务器收到消息: 9526*56 客户端收到结果:533456
相关推荐
二、java NIO,AIO编程视频教程 1、java NIO,AIO编程_01.flv 2、java NIO,AIO编程_02.flv 3、java NIO,AIO编程_03.flv 4、java NIO,AIO编程_04.flv 5、java NIO,AIO编程_05.flv 三、Java语言基础教程-Java NIO...
Java中的异步套接字编程,也称为非阻塞I/O(Non-blocking I/O, NIO)或异步I/O(Asynchronous I/O, AIO),是Java在JDK 7引入的一种高级I/O模型,它极大地提高了网络编程的效率。AIO的主要目标是提供一种方法,使得...
"Smart-Socket"是一个开源的Java AIO框架,它提供了高效、稳定且易于使用的网络通信解决方案。这个框架基于Java的异步I/O(Asynchronous Input/Output)模型,旨在简化多路复用的网络编程,尤其适用于高并发、低延迟...
9. **网络IO**:Java的NIO(Non-blocking I/O)和AIO(Asynchronous I/O)为网络编程提供了高效的I/O模型,特别是对于高并发场景,能够显著提升性能。 10. **实战案例**:书中可能包含各种实际的网络应用示例,如...
在这个实例集合中,你将发现一系列的编程示例,涵盖了Java网络编程的基础到进阶内容。这些实例可以帮助你深入理解和实践Java在处理网络通信时的各种机制。 首先,让我们了解Java中的网络编程基础。Java提供了丰富的...
在Java编程领域,异步I/O(Asynchronous Input/Output,简称AIO)是一种高效的I/O处理模型,它允许程序在等待数据准备就绪时执行其他任务,而不是直接阻塞等待。AIO在Java中也被称为NIO.2,是Java NIO(New I/O)的...
Java 网络IO编程总结(BIO、NIO、AIO均含完整实例代码) Java 网络IO编程是 Java 编程语言中最重要的知识点之一,涉及到网络编程的各种技术和模型。本篇文章主要介绍了 Java 网络IO编程总结,包括 BIO、NIO 和 AIO ...
《Java2.0网络多线程编程实例教程》是一本由李荣贵等人编写的书籍,专注于Java2.0(即Java SE 2)平台下的网络编程和多线程技术。该书通过丰富的实例,旨在帮助读者深入理解和掌握这两项核心的Java开发技能。 在...
本文将深入探讨Java中的三种主要通讯模型:BIO( Blocking I/O)、NIO(Non-blocking I/O)和AIO(Asynchronous I/O),并结合实际的代码示例进行综合演练。 **一、BIO(阻塞I/O)** 1. **概念**:BIO是Java早期的...
1. BIO、NIO、AIO的区别:BIO是阻塞式IO,NIO是非阻塞式IO,AIO是异步IO。 2. Files的常用方法:Files类提供了许多文件操作方法。 反射机制 1. 反射机制的优缺点:反射机制可以动态地调用类和方法,但也可能会...
Java客户端实现Kafka生产者与消费者实例 kafka的副本机制及选举原理剖析 基于kafka实现应用日志实时上报统计分析 RabbitMQ 初步认识RabbitMQ及高可用集群部署 详解RabbitMQ消息分发机制及主题消息分发 ...
在Java中,AIO相关的API主要包含在`java.nio.channels.AsynchronousServerSocketChannel`和`java.nio.channels.AsynchronousSocketChannel`等类中。 要实现一个基于AIO的HTTP服务器,首先需要创建一个`...
在Java中,`java.net.Socket`类用于创建TCP连接,客户端通常会创建一个Socket实例,指定服务器的IP地址和端口号,然后通过Socket进行数据的读写。 5. **gt、wyf** 这两个文件名可能是个人或者项目名称,具体含义...
### Java分布式之RMI简介及实例 #### RMI概述 远程方法调用(Remote Method Invocation,简称RMI)是Java平台提供的一种分布式计算框架,它允许开发者创建可以在网络上跨多台计算机运行的对象。RMI的目标是使得...
BIO NIO 和 AIO 的区别什么是流 流的分类 节点流和处理流 Java IO 的核心类 File Java IO 流对象 字节流对象InputStream OutputStream 字符流对象Reader Writer 字节流与字符流的转换新潮的 NIO 缓冲区(Buffer)通道...
- Java的IO流分为字节流和字符流,支持BIO、NIO和AIO模型。 - 反射允许程序在运行时检查和操作类、对象和方法,但可能影响性能和安全性。 - `hashCode()`和`equals()`对于对象比较和集合操作至关重要,当重写`...
* BIO、NIO、AIO 是 Java 中的 I/O 模式。 五、ArrayList 5.1 ArrayList 简介 * ArrayList 是一个动态数组,提供了对数组的操作方法。 5.2 ArrayList 核心源码 * ArrayList 的核心实现是基于数组的动态扩容。 ...
NIO(Non-blocking I/O)提供了更高效的数据传输,AIO(Asynchronous I/O)进一步实现了异步I/O操作。 这只是Java中高级核心知识的冰山一角,实际学习中还需深入研究反射、网络编程、数据库连接、设计模式、并发...