NIO学习:异步IO实例
工作模式:

客户端代码:
package demos.nio.socketChannel; import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Arrays;
import java.util.Iterator;
import java.util.Set; import org.apache.log4j.Logger; /**
* 非阻塞 Socket 客户端
* 通过一个线程监听管理所有通道
*
*/
public class Client {
private Logger logger=Logger.getLogger(Client.class);
/** * 服务器Ip */
private String ip;
/** * 服务器端口 */
private int port;
/** * 控制是否监听通道事件 */
private volatile boolean isListenable;
/** * 缓冲区大小 */
private final int bufferSize = 1024;
/** * 选择器每次阻塞监听的最大时间 */
private final int selectorTime = 1000;
/** * 创建Selector来管理通道事件 */
private Selector selector; public Client(String ip, int port) {
this.ip = ip;
this.port = port;
// 监听器
try {
selector = Selector.open();
} catch (IOException e) {
e.printStackTrace();
}
} public void send(String msg) {
send(msg.getBytes());
} /**
* 发送数据
*
* @param data
*/
public void send(byte[] data) {
try {
// 打开一个网络通道
SocketChannel socketChannel = SocketChannel.open();
// 设置通道为非阻塞
socketChannel.configureBlocking(false);
// 注册管道事件,监听连接成功
SelectionKey key = socketChannel.register(selector,
SelectionKey.OP_CONNECT);
// 将发送数据附加在SelectionKey上
key.attach(ByteBuffer.wrap(data));
// 建立连接
socketChannel.connect(new InetSocketAddress(ip, port)); //当第一个通道被注册到Selector上时,开启守护线程开始监听通道的事件
if (!isListenable&&selector.keys().size() == 1) {
//开启监听
isListenable = true;
// 开一个线程监听所有通道的事件
Thread thread = new Thread(this.new SelectionTask());
thread.start();
}
} catch (Exception e) {
e.printStackTrace();
}
} /**
* 往通道中写入数据
* 当通道为非阻塞时它都是可写的,所以如果需要写数据,则注册监听写事件即可
* @param selectionKey
*/
private void writeData(SelectionKey selectionKey) {
selectionKey.interestOps(selectionKey.interestOps()
| SelectionKey.OP_WRITE);
selectionKey.selector().wakeup();
} public void closeListen() {
logger.debug("关闭监听");
this.isListenable = false;
this.selector.wakeup();
} /**
* 判断是否继续监听
* 如果selector中没有可监听的通道,则取消监听
* @return
*/
private boolean isListen() {
return this.isListenable && (this.selector.keys().size() > 0);
} /**
* 监听任务
*
* @author root
*
*/
class SelectionTask implements Runnable { /**
* 处理监听到的事件
*
* @param selectionKey
* @throws IOException
*/
private void handleSelectionKey(SelectionKey selectionKey)
throws IOException {
/** * 缓冲区 */
ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize);
SocketChannel channel = (SocketChannel) selectionKey.channel();
if (!selectionKey.isValid()) {
return;
}
if (selectionKey.isConnectable()) {
if (!channel.isConnectionPending()) {
return;
}
channel.finishConnect();
logger.debug("与服务器连接成功");
// 连接成功后开始写数据
writeData(selectionKey);
} else if (selectionKey.isReadable()) {
//循环把接受到的数据写入到内存中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
byteBuffer.clear();
while (channel.read(byteBuffer) > 0) {
byteBuffer.flip();
byte[] b = Arrays.copyOf(byteBuffer.array(), byteBuffer
.limit());
outputStream.write(b);
byteBuffer.clear();
}
logger.debug("客户端收到信息:"
+ new String(outputStream.toByteArray()));
// 使Selector注销对该Channel的监听
selectionKey.cancel();
} else if (selectionKey.isWritable()) {
logger.debug("写出数据");
ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
if (buffer == null) {
return;
}
while (buffer.hasRemaining()) {
channel.write(buffer);
}
selectionKey.interestOps(SelectionKey.OP_READ);
}
} @Override
public void run() {
try {
// 控制是否监听
while (isListen()) {
//判断是否监听到了感兴趣的事件
if (selector.select(selectorTime) <= 0) {
continue;
}
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()) {
handleSelectionKey(iterator.next());
//处理完selectionKey后需要移除它
iterator.remove();
}
}
selector.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void main(String[] args) throws InterruptedException {
Client socket = new Client("127.0.0.1", 8686);
socket.send("hello");
}
}
NIO学习:异步IO实例的更多相关文章
- Python并发编程之学习异步IO框架:asyncio 中篇(十)
大家好,并发编程 进入第十章.好了,今天的内容其实还挺多的,我准备了三天,到今天才整理完毕.希望大家看完,有所收获的,能给小明一个赞.这就是对小明最大的鼓励了.为了更好地衔接这一节,我们先来回顾一下上 ...
- 异步IO实例
#include <stdio.h> #include <stdlib.h> #include <errno.h> #include <string.h> ...
- Java网络编程和NIO详解5:Java 非阻塞 IO 和异步 IO
Java网络编程和NIO详解5:Java 非阻塞 IO 和异步 IO Java 非阻塞 IO 和异步 IO 转自https://www.javadoop.com/post/nio-and-aio 本系 ...
- Python(3)---从迭代器到异步IO
whenif 关注 2017.02.13 23:48* 字数 1750 阅读 250评论 0喜欢 8 目录 1. 迭代(iteration)与迭代器(iterator) 1.1 构建简单迭代器 1.2 ...
- NIO 之阻塞IO和非阻塞IO(转载)
阻塞模式 IO 我们已经介绍过使用 Java NIO 包组成一个简单的客户端-服务端网络通讯所需要的 ServerSocketChannel.SocketChannel 和 Buffer,我们这里整合 ...
- 异步IO与回调
最好了解 Java NIO 中 Buffer.Channel 和 Selector 的基本操作,主要是一些接口操作,比较简单. 本文将介绍非阻塞 IO 和异步 IO,也就是大家耳熟能详的 NIO 和 ...
- netty权威指南学习笔记一——NIO入门(2)伪异步IO
在上一节我们介绍了四种IO相关编程的各个特点,并通过代码进行复习了传统的网络编程代码,伪异步主要是引用了线程池,对BIO中服务端进行了相应的改造优化,线程池的引入,使得我们在应对大量客户端请求的时候不 ...
- Java NIO 学习笔记(六)----异步文件通道 AsynchronousFileChannel
目录: Java NIO 学习笔记(一)----概述,Channel/Buffer Java NIO 学习笔记(二)----聚集和分散,通道到通道 Java NIO 学习笔记(三)----Select ...
- JAVA NIO学习一:NIO简介、NIO&IO的主要区别
在前面学习了IO之后,今天我们开始进入NIO学习环节,首先我们会NIO做一个简单的介绍,让大家认识NIO,然后会和IO进行一个对比认识进行区分.好了,下面我们就开始学习: 一.NIO简介 1.概述 从 ...
随机推荐
- Android:DES加密
private static final String KEY = "xxxxxx"; // KEY的字节长度必须超过24 public DESUtil(){ super(); } ...
- ruby2.2.2 源代码阅读笔记
这是win32下的结构 从ruby_setup开始阅读 Ruby对象内存结构 RVALUE是一个union,内含ruby所有结构体(RBasic RObject RClass RFloat RStri ...
- 使用 HTML5、CSS3 和 MathML 在 EPUB 3 中制作版式丰富的出版物
探索用于高级排版和印刷的新一代开放电子书标准 EPUB 3.0 是最新的行业标准 XML 电子书格式,它采用了 HTML5 和 CSS3,因而融入了现代 Web 技术.它重点关注 XML 驱动的工具包 ...
- Mysql监控工具小集合
介绍一些常见的Mysql监控工具. Cacti Cacti是 一套基于PHP,MySQL,SNMP及RRDTool开发的网络流量监测图形分析工具.它通过snmpget来获取数据,使用 RRDtool绘 ...
- 知识面 z
http://blog.csdn.net/sxhelijian/article/details/23163683 有了较宽和知识面,面对复试中不知道的问题,回答可以是:“这个问题,直接回答我没有把握, ...
- HDU3047 Zjnu Stadium 带权并查集
转:http://blog.csdn.net/shuangde800/article/details/7983965 #include <cstdio> #include <cstr ...
- Linux使用sudo提权时,出现xx 不在 sudoers 文件中。此事将被报告。visudo 命令简单介绍。
在使用 sudo 临时提权时,出现:不在 sudoers 文件中.此事将被报告. 可以使用 visudo命令 来配置/etc/sudoers文件,将目标用户赋予使用sudo命令的能力. visudo命 ...
- Error -26359: Function not allowed within a concurrent group
Error -26359: Function not allowed within a concurrent group 疑问: 基于url录制的脚步能用检查点么? 疑问: web_set_max ...
- Clean Code–Chapter 7 Error Handling
Error handling is important, but if it obscures logic, it's wrong. Use Exceptions Rather Than Return ...
- HW5.14
public class Solution { public static void main(String[] args) { System.out.printf("%s\t%s\n&qu ...