Java中NIO及基础实现
2024-09-01 10:26:29
NIO:同步非阻塞IO
来源:BIO是同步阻塞IO操作,当线程在处理任务时,另一方会阻塞着等待该线程的执行完毕,为了提高效率,,JDK1.4后,引入NIO来提升数据的通讯性能
NIO中采用Reactor设计模式,注册的汇集点为Selector,NIO有三个主要组成部分:Channel(通道)、Buffer(缓冲区)、Selector(选择器)
Reactor设计模式:Reactor模式是一种被动事件处理模式,即当某个特定事件发生时触发事件,可参考,https://blog.csdn.net/feimataxue/article/details/7642638,https://www.cnblogs.com/bitkevin/p/5724410.html
NIO采用了轮询的方式来观察事件是否执行完毕,如:A让B打印某个文件,BIO会一直等待着B返回,期间自己不做其他事情,而NIO则会不断的询问B是否完成,未完成则处理自己的时,直至B完成
Channel(通道):Channel是一个对象,可以通过它读取和写入数据
Selector(对象选择器): Selector是一个对象,它可以注册到很多个Channel上,监听各个Channel上发生的事件,并且能够根据事件情况决定Channel读写
代码实现:(此实现参考网络上可用的例子)
NIO客户端实现:
package com.learn.nio.client; import com.study.info.HostInfo;
import com.study.util.InputUtil; import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel; public class NIOEchoClient { public static void main(String[] args) throws Exception{
SocketChannel clientChannel = SocketChannel.open();
clientChannel.connect(new InetSocketAddress(HostInfo.HOST_NAME,HostInfo.PORT));
ByteBuffer buffer = ByteBuffer.allocate(50);
boolean flag = true;
while (flag){
buffer.clear();
String input = InputUtil.getString("请输入待发送的信息:").trim();
buffer.put(input.getBytes()); //将数据存入缓冲区
buffer.flip(); // 重置缓冲区
clientChannel.write(buffer); //发送数据
buffer.clear();
int read = clientChannel.read(buffer);
buffer.flip();
System.err.print(new String(buffer.array(), 0, read));
if("byebye".equalsIgnoreCase(input)){
flag = false;
}
}
clientChannel.close();
}
}
NIO服务端实现:
package com.learn.nio.server; import com.study.info.HostInfo; import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class NIOEchoServer { private static class EchoClientHandle implements Runnable { //客户端
private SocketChannel clientChannel;
// 循环结束标记
private boolean flag = true;
public EchoClientHandle(SocketChannel clientChannel){
this.clientChannel = clientChannel;
} @Override
public void run() {
ByteBuffer byteBuffer = ByteBuffer.allocate(50);
try {
while (this.flag){
byteBuffer.clear();
int read = this.clientChannel.read(byteBuffer);
String msg = new String(byteBuffer.array(), 0, read).trim();
String outMsg = "【Echo】" + msg + "\n"; // 回应信息
if("byebve".equals(msg)){
outMsg = "会话结束,下次再见!";
this.flag = false;
}
byteBuffer.clear();
byteBuffer.put(outMsg.getBytes()); //回传信息放入缓冲区
byteBuffer.flip();
this.clientChannel.write(byteBuffer);// 回传信息
}
}catch (Exception e){
e.printStackTrace();
}
}
} public static void main(String[] args) throws Exception{
// 为了性能问题及响应时间,设置固定大小的线程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
// NIO基于Channel控制,所以有Selector管理所有的Channel
ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
// 设置为非阻塞模式
serverSocketChannel.configureBlocking(false);
// 设置监听端口
serverSocketChannel.bind(new InetSocketAddress(HostInfo.PORT));
// 设置Selector管理所有Channel
Selector selector = Selector.open();
// 注册并设置连接时处理
serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
System.out.println("服务启动成功,监听端口为:" + HostInfo.PORT);
// NIO使用轮询,当有请求连接时,则启动一个线程
int keySelect = 0;
while ((keySelect = selector.select()) > 0){
Set<SelectionKey> selectionKeys = selector.selectedKeys();
Iterator<SelectionKey> iterator = selectionKeys.iterator();
while (iterator.hasNext()){
SelectionKey next = iterator.next();
if(next.isAcceptable()){ // 如果是连接的
SocketChannel accept = serverSocketChannel.accept();
if(accept != null){
executorService.submit(new EchoClientHandle(accept));
}
iterator.remove();
}
}
}
executorService.shutdown();
serverSocketChannel.close();
}
}
工具类:
package com.study.util; import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader; public class InputUtil {
private static final BufferedReader KEYBOARD_INPUT = new BufferedReader(new InputStreamReader(System.in)); private InputUtil(){
} public static String getString(String prompt){
boolean flag = true; //数据接受标记
String str = null;
while (flag){
System.out.println(prompt);
try {
str = KEYBOARD_INPUT.readLine(); // 读取一行数据
if(str == null || "".equals(str)){
System.out.println("数据输入错误,不允许为空!");
}else {
flag = false;
}
} catch (IOException e) {
e.printStackTrace();
}
}
return str;
}
}
package com.study.info; public calss HostInfo {
public static final String HOST_NAME = "localhost";
public static final int PORT = 9999;
}
NIO结构参考文章: https://www.cnblogs.com/sxkgeek/p/9488703.html#_label2
最新文章
- String path = request.getContextPath(); String basePath = request.getScheme() + ";://"; + request.getServerName() + ";:"; + request.getServerPort() + path + ";/";;作用!!!!!
- jQuery演示8种不同的图片遮罩层动画效果
- c#导出bugfree3.0的数据到禅道
- 版本控制--github相关
- phpexcel生成excel并下载
- hdu 2067
- JAVA并发的性能调整
- 文件上传插件Uploadify在Struts2中的应用,完整详细实例
- (转载)Linux网络配置和setup工具包安装
- TextView总结
- UI经验
- 在android系统上写C语言程序--开机启动该程序不进入安卓系统
- python3 经典排序方法
- spark之java程序开发
- wxWidgets 在 Linux 下开发环境配置
- XGBOOST应用及调参示例
- Java学习笔记31(IO:Properties类)
- python通过xlwt模块直接在网页上生成excel文件并下载
- C# 发送HTTP请求超时解决办法
- JavaScript中hoisting(悬置/置顶解析/预解析) 实例解释,全局对象,隐含的全局概念
热门文章
- RobotFramework自动化测试框架-MongoDBLibrary库的使用
- (转载)非常完善的Log4net配置详细说明
- HTML5有哪些新特性,移除了哪些元素?如何处理HTML5新标签的浏览器兼容性问题?如何区分HTML和HTML5?
- Qt 模拟一个导航定位系统
- VS中一些提高编码效率的快捷键
- 5.1、顺序队列(java实现)
- Vue最全指令大集合————VUE
- 42 (OC)* 字典实现原理--哈希原理
- 实操:Could not autowire No beans of &#39;FastDFS Client&#39; type found 的解决方法
- 从零开始使用 Webpack 搭建 Vue 开发环境