Netty学习——实战篇1 BIO、NIO入门demo 备注

 1 BIO 实战代码 

@Slf4j
public class BIOServer {public static void main(String[] args) throws IOException {//1 创建线程池ExecutorService threadPool = Executors.newCachedThreadPool();//2 创建ServerSocketServerSocket serverSocket = new ServerSocket(8000);log.info("服务器已启动成功");//3 监听,等待客户端连接while(true){log.info("线程id:{}",Thread.currentThread().getId());log.info("等待连接...");//4 客户端连接后,创建一个线程,与客户端通信final Socket socket = serverSocket.accept();threadPool.execute(new Runnable() {@Overridepublic void run() {handler(socket);}});}}//编写一个handler方法,与客户端通信public static  void handler(Socket socket){try {log.info("线程id:{}",Thread.currentThread().getId());//创建一个byte[]数组byte[] bytes = new byte[1023];//通过socket获取输入流InputStream inputStream = socket.getInputStream();//循环读取客户端发送的消息while(true){int read = inputStream.read(bytes);if(read != -1){System.out.println(new String(bytes,0,read));}else{break;}}}catch (Exception e){e.printStackTrace();}finally {try {log.info("关闭与客户端的连接");socket.close();} catch (IOException e) {throw new RuntimeException(e);}}}
}

        运行结果

8621025cda1d47839eed300130b406cd.png

2 NIO实战

2.1 Buffer实战

@Slf4j
public class BasicBuffer {public static void main(String[] args) {//1 创建一个BufferIntBuffer buffer = IntBuffer.allocate(10);//2 往Buffer存储数据for (int i = 0; i < buffer.capacity(); i++) {buffer.put(i * 2);}//3 Buffer读写切换buffer.flip();//4 Buffer 读数据while(buffer.hasRemaining()){log.info("{}",buffer.get());}}
}

 

2.2 FileChannel实战

        使用NIO的FileChannel和ByteBuffer,把一段文字写入到指定的文件中。

//把文字写入到指定文件中
public class FileChannelWrite{public static void main(String[] args) throws IOException {//1 指定文字String str = "hello,孔乙己";//2 创建一个输出流FileOutputStream fileOutputStream = new FileOutputStream("D:\\develop\\java-base\\test\\test01.txt");//3 通过输出流创建FileChanneljava.nio.channels.FileChannel fileChannel = fileOutputStream.getChannel();//4 创建一个缓冲区ByteBuffer buffer = ByteBuffer.allocate(1024);//5 把文字放入缓冲区buffer中buffer.put(str.getBytes());//6 对buffer进行翻转buffer.flip();//7 把buffer的数据写入到FileChannelfileChannel.write(buffer);//8 关闭流fileOutputStream.close();}
}

 

        使用NIO的FileChannel和Bytebuffer,读取指定文件中的内容,并打印到控制台

@Slf4j
public class FileChannelRead {public static void main(String[] args) throws IOException {//1 创建输入流File file = new File("D:\\develop\\java-base\\test\\test01.txt");FileInputStream fileInputStream = new FileInputStream(file);//2 通过输入流创建FileChannelFileChannel fileChannel = fileInputStream.getChannel();//3 创建缓冲区ByteBuffer buffer = ByteBuffer.allocate((int) file.length());//4 把通道的数据读取到缓冲区fileChannel.read(buffer);//5 把bytebuffer 转成 stringlog.info("文件的内容是: {}",new String(buffer.array()));//6 关闭输入流fileInputStream.close();}
}

 

        使用一个Buffer,FileChannel和read/write方法,完成文件的拷贝 .

public class FileChannelCopy {public static void main(String[] args) throws IOException {FileInputStream fileInputStream = new FileInputStream("D:\\develop\\java-base\\test\\source.txt");FileChannel inputChannel = fileInputStream.getChannel();FileOutputStream fileOutputStream = new FileOutputStream("D:\\develop\\java-base\\test\\target.txt");FileChannel outChannel = fileOutputStream.getChannel();ByteBuffer buffer = ByteBuffer.allocate(1024);while (true){buffer.clear();int read = inputChannel.read(buffer);if(read == -1){break;}buffer.flip();outChannel.write(buffer);}fileInputStream.close();fileOutputStream.close();}
}

        使用transferFrom方法拷贝文件 

public class FileChannelCopy01 {public static void main(String[] args) throws IOException {FileInputStream fileInputStream = new FileInputStream("D:\\develop\\java-base\\test\\source.png");FileOutputStream fileOutputStream = new FileOutputStream("D:\\develop\\java-base\\test\\dest.png");FileChannel inChannel = fileInputStream.getChannel();FileChannel outChannel = fileOutputStream.getChannel();outChannel.transferFrom(inChannel,0,inChannel.size());fileInputStream.close();fileOutputStream.close();}
}

2.3 MappedByteBufer

         MappedByteBufer 可以让文件直接在内存(堆外内存)修改,操作系统不需要再拷贝一次

//原来的内容是:hello,孔乙己
//修改后的内容是:HelLo,孔乙己
public class MappedByteBuffer {public static void main(String[] args) throws IOException {RandomAccessFile randomAccessFile = new RandomAccessFile("D:\\develop\\java-base\\test\\test01.txt", "rw");FileChannel channel = randomAccessFile.getChannel();java.nio.MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, 5);map.put(0,(byte) 'H');map.put(3,(byte) 'L');randomAccessFile.close();}
}

2.4 ServerSocketChannel和SocketChannel

@Slf4j
public class ServerSocketChannelAndSocketChannel {public static void main(String[] args) throws IOException {//1 使用ServerSocketChannel和SocketChannel 网络ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();InetSocketAddress address = new InetSocketAddress(8000);//2 绑定端口到socket,并启动serverSocketChannel.socket().bind(address);//3 创建 ByteBuffer数组ByteBuffer[] buffers = new ByteBuffer[2];buffers[0] = ByteBuffer.allocate(5);buffers[1] = ByteBuffer.allocate(3);//4 等待客户端连接SocketChannel socketChannel = serverSocketChannel.accept();int messageLength = 8;//假定从客户端接收到8个字节//5 循环读取while(true){int byteRead = 0;while(byteRead < messageLength){long read = socketChannel.read(buffers);byteRead += read;log.info("byteRead = ,{}",byteRead);//使用流打印,查看当前的这个buffer的position和limitArrays.asList(buffers).stream().map(buffer -> "position = " +buffer.position() +",limit = " + buffer.limit()).forEach(System.out::println);}// 6 将所有的buffer进行翻转Arrays.asList(buffers).forEach(buffer -> buffer.flip());// 将数据读取到客户端long byteWrite = 0;while(byteWrite < messageLength){long l = socketChannel.write(buffers);byteWrite += l;}//将所有的buffer进行翻转Arrays.asList(buffers).forEach(buffer ->{buffer.clear();});log.info("byteRead = ,{},byteWrite = {},messageLength = {}",byteRead,byteWrite,messageLength);}}
}

2.5 使用NIO开发服务端和客户端

        NIOServer.java 

 

@Slf4j
public class NIOServer {public static void main(String[] args) throws Exception{//1 创建ServerSocketChannelServerSocketChannel serverSocketChannel = ServerSocketChannel.open();//2 创建Selector对象Selector selector = Selector.open();//3 绑定端口 8000,在服务器监听serverSocketChannel.socket().bind(new InetSocketAddress(8000));//4 ServerSocketChannel设置为非阻塞serverSocketChannel.configureBlocking(false);//5 把ServerSocketChannel的OP_ACCEPT注册到selectorserverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);log.info("ServerSocketChannel已注册到Selector上");// 6 循环,等待客户端连接while(true){//7 等待一秒,如果没有事件发生,就返回if(selector.select(1000) == 0){log.info("等待1秒,没有客户端连接");continue;}//8 如果有事件发生,就获取selectedKyes,返回关注事件的集合Set<SelectionKey> selectededKeys = selector.selectedKeys();Iterator<SelectionKey> keyIterator = selectededKeys.iterator();//9 遍历selectedKeys集合,获取事件类型while(keyIterator.hasNext()){SelectionKey key = keyIterator.next();if(key.isAcceptable()){log.info("客户端连接成功");//10_1 如果是OP_ACCEPT事件,证明有新的客户端连接,为该客户端创建一个SocketChannelSocketChannel socketChannel = serverSocketChannel.accept();socketChannel.configureBlocking(false);//10_1_1 将SocketChannel注册到selector上,事件类型是OP_READ,并绑定一个缓冲区socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));}if(key.isReadable()){//10_2  如果是OP_READ事件,通过selectedKey 反向获取 SocketChannelSocketChannel channel =(SocketChannel) key.channel();//10_2_1  获取该channel绑定的buffer,并读取ByteBuffer buffer = (ByteBuffer)key.attachment();channel.read(buffer);log.info("从客户端读取的数据是: {}",new String(buffer.array()));}//11 移除selectedKey,防止重复操作keyIterator.remove();}}}
}

        NIOClient.java

 

@Slf4j
public class NIOClient {public static void main(String[] args) throws Exception {//1 创建SocketChannelSocketChannel socketChannel = SocketChannel.open();//2 设置非阻塞模式socketChannel.configureBlocking(false);//3  提供服务器的ip和端口InetSocketAddress address = new InetSocketAddress("127.0.0.1", 8000);//4 连接服务器if(!socketChannel.connect(address)){// 4_1 连接失败while(!socketChannel.finishConnect()){log.info("连接需要时间,此时客户端不会阻塞,可以做其他工作。。。");}}//4_2 连接成功,发送数据String str = "hello ,孔乙己";ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());socketChannel.write(buffer);System.in.read();}
}

        运行结果:

cac6746784044121871985398c1944f7.png

 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/815211.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【嵌入式基础知识学习】AD/DA—数模/模数转换

AD/DA—数模/模数转换概念 数字电路只能处理二进制数字信号&#xff0c;而声音、温度、速度和光线等都是模拟量&#xff0c;利用相应的传感器&#xff08;如声音用话筒&#xff09;可以将它们转换成模拟信号&#xff0c;然后由A/D转换器将它们转换成二进制数字信号&#xff0c…

6个Python迭代器及生成器酷炫实例

大家好&#xff0c;今天我们要一起探索Python中的六个神奇工具&#xff1a;迭代器和生成器。它们就像魔法棒&#xff0c;能让我们优雅地处理大量数据&#xff0c;既节省内存又高效。别担心&#xff0c;我会用最接地气的语言和简单易懂的代码示例来带你一探究竟&#xff01; 1.…

音视频学习—音视频理论基础(1)

音视频学习—音视频理论基础&#xff08;1&#xff09; 一、音视频处理流程1.1 音频处理流程1.2 视频处理流程1.3 音视频数据流转1.4 为什么音视频采集完之后&#xff0c;不能直接传输&#xff0c;要进行编码&#xff1f;1.5 模数转换1.6 PCM1.7 WAV 总结 一、音视频处理流程 音…

漫途水产养殖水质智能监测方案,科技助力养殖业高效生产!

随着水产养殖业的蓬勃发展&#xff0c;水质和饲料等多重因素逐渐成为影响其持续健康发展的关键因素。由于传统养殖模式因监控和调节手段不足&#xff0c;往往造成养殖环境的恶化。需要通过智能化养殖&#xff0c;调控养殖环境&#xff0c;实现养殖的精细化管理模式&#xff0c;…

python列表的删除 del、pop、remove

在Python中&#xff0c;del、pop()和remove()是用于操作列表的方法&#xff0c;它们在不同的情况下有不同的用途和适用性。 del语句&#xff1a; 使用del语句可以删除列表中指定索引的元素&#xff0c;或者可以用来删除整个列表。适用情况&#xff1a; 当你知道要删除的元素的索…

mysql 查询实战1-解答

对的mysql 查询实战1-题目&#xff0c;进行解答 1&#xff0c;查询部门工资最高的员工 1&#xff0c;按部门分组&#xff0c;先查出部门薪资最高的&#xff1a; select dept_id, max(salary) from employeegroup by dept_id; 2&#xff0c;等值连接查询&#xff1a;关联查部门…

【vue】生命周期函数

组件在其生命周期中的特定时候&#xff0c;会执行的函数 别忘了导入 如&#xff1a;import { ref, onMounted, onUpdated } from vue; 生命周期函数 挂载阶段 onBeforeMount&#xff1a;组件挂载到DOM之前调用onMount&#xff1a;组件挂载成功后调用 更新阶段 onBeforeUpdat…

实现一个 console.table

实现一个类似 console.table 的效果。 输入示例 [{name: "hdl",age: 1,city: "wh",},{name: "hdljshfjlhsf",age: 177,city: "whsh",},{name: "hdljsh",age: 1778,city: "sjfh skj",}, ];输出示例&#xff1a; 左…

Bug的定义生命周期

1、bug的定义 你们觉得bug是什么? 软件的Bug狭义概含是指软件程序的漏洞或缺陷&#xff0c; 广义概念除此之外还包括测试工程师或用户所发现和提出的软件可改进的细节(增强性&#xff0c;建议性)、或 与需求文档存在差异的功能实现等。 我们的职责就是&#xff0c;发现这些B…

Orangepi Zero2 wiringPi外设库SDK安装

文章目录 1. sdk 下载2. sdk 使用 1. sdk 下载 1、使用git 下载 # apt-get update # apt-get install -y git # git clone https://github.com/orangepi-xunlong/wiringOP.git2、手动下载并上传 下载连接 https://github.com/orangepi-xunlong/wiringOP 选master分支 上传到…

【vue】跨组件通信--依赖注入

import { provide,inject } from vue provide&#xff1a;将父组件的数据传递给所有子组件&#xff08;子孙都有&#xff09;inject&#xff1a;接收provide 项目文件结构 App.vue是Header.vue的父组件&#xff0c;Header.vue是Nav.vue的父组件 传值过程 App.vue <tem…

React中state和props有什么区别?

React中state和props有什么区别&#xff1f; 1. state2. props3. state和props的区别4. 案例4.1使用state4.2 使用props 5. defaultProps和propTypes5.1 defaultProps5.2 propTypes 在React中&#xff0c;state和props是两个核心概念&#xff0c;它们代表了组件的状态和属性。虽…

Python学习笔记20 - 模块

什么叫模块 自定义模块 Python中的包 Python中常用的内置模块 第三方模块的安装与使用

计算机网络——DHCP协议

前言 本博客是博主用于复习计算机网络的博客&#xff0c;如果疏忽出现错误&#xff0c;还望各位指正。 这篇博客是在B站掌芝士zzs这个UP主的视频的总结&#xff0c;讲的非常好。 可以先去看一篇视频&#xff0c;再来参考这篇笔记&#xff08;或者说直接偷走&#xff09;。 …

funasr 麦克风实时流语音识别;模拟vad检测单独输出完整每句话

参考: https://github.com/alibaba-damo-academy/FunASR chunk_size 是用于流式传输延迟的配置。[0,10,5] 表示实时显示的粒度为 1060=600 毫秒,并且预测的向前信息为 560=300 毫秒。每个推理输入为 600 毫秒(采样点为 16000*0.6=960),输出为相应的文本。对于最后一个语音…

【学习】软件测试需求分析要从哪些方面入手

软件测试需求分析是软件测试过程中非常重要的一个环节&#xff0c;它是为了明确软件测试的目标、范围、资源和时间等要素&#xff0c;以确保软件测试的有效性和全面性。本文将从以下几个方面对软件测试需求分析进行详细的阐述&#xff1a; 一、软件测试目标 软件测试目标是指…

机器学习周记(第三十四周:文献阅读[GNet-LS])2024.4.8~2024.4.14

目录 摘要 ABSTRACT 1 论文信息 1.1 论文标题 1.2 论文摘要 1.3 论文模型 1.3.1 数据处理 1.3.2 GNet-LS 2 相关代码 摘要 本周阅读了一篇时间序列预测论文。论文模型为GNet-LS&#xff0c;主要包含四个模块&#xff1a;粒度划分模块&#xff08;GD&#xff09;&…

RabbitMQ消息模型之Work消息模型

Work消息模型 * work模型&#xff1a; * 多个消费者消费同一个队列中的消息&#xff0c;每个消费者获取到的消息唯一&#xff0c;且只能消费一次 * 作用&#xff1a;提高消息的消费速度&#xff0c;避免消息的堆积 * 默认采用轮询的方式分发消息 * 如果某…

无人机/飞控--ArduPilot、PX4学习记录(5)

这几天看dronekit&#xff0c;做无人机失控保护。 PX4官网上的经典案例&#xff0c;我做了很多注解&#xff0c;把代码过了一遍。 无人机具体执行了&#xff1a; 先起飞&#xff0c;飞至正上空10m->向北移动10m->向东移动10m->向南移动10m->向西移动10m->回到初…

白学的小知识[属性操作.节点遍历操作.CSS-DOM操作]

属性操作&#xff1a; attr() 用来获取与设置元素属性 。 $newNode4.attr("alt");//获取alt属性值 //或 $("img").attr({width:"50px",height:"100px"});//设置width、height属性的值 $("img[idmyimg]").attr("src&quo…