当前位置: 首页 > news >正文

netty之基础aio,bio,nio

前言


在Java中,提供了一些关于使用IO的API,可以供开发者来读写外部数据和文件,我们称这些API为Java IO。IO是Java中比较重要知识点,且比较难学习的知识点。并且随着Java的发展为提供更好的数据传输性能,目前有三种IO共存;分别是BIO、NIO和AIO。
在这里插入图片描述
同步阻塞I/O模式
是一个比较传统的通信方式,模式简单,使用方便。但并发处理能力低,通信耗时,依赖网速。
同步非阻塞模式
NIO 与原来的 I/O 有同样的作用和目的, 他们之间最重要的区别是数据打包和传输的方式。原来的 I/O 以流的方式处理数据,而 NIO 以块的方式处理数据。
异步非阻塞I/O模型
是一种非阻塞异步的通信模式。在NIO的基础上引入了新的异步通道的概念,并提供了异步文件通道和异步套接字通道的实现。

aio


目录结构如下图
在这里插入图片描述

新建客服端启动类 AioClient

public class AioClient {public static void main(String[] args) throws Exception {AsynchronousSocketChannel socketChannel = AsynchronousSocketChannel.open();Future<Void> future = socketChannel.connect(new InetSocketAddress("192.168.108.89", 7397));System.out.println("com.lm.netty01.aio client start done. {码农明哥 | 欢迎关注&获取源码}");future.get();socketChannel.read(ByteBuffer.allocate(1024), null, new AioClientHandler(socketChannel, Charset.forName("GBK")));Thread.sleep(100000);}}

客户端消息处理器类

public class AioClientHandler extends ChannelAdapter {public AioClientHandler(AsynchronousSocketChannel channel, Charset charset) {super(channel, charset);}@Overridepublic void channelActive(ChannelHandler ctx) {try {System.out.println("程序员码农 | 链接报告信息:" + ctx.channel().getRemoteAddress());//通知客户端链接建立成功} catch (IOException e) {e.printStackTrace();}}@Overridepublic void channelInactive(ChannelHandler ctx) {}@Overridepublic void channelRead(ChannelHandler ctx, Object msg) {System.out.println("码农明哥 | 服务端收到:" + new Date() + " " + msg + "\r\n");ctx.writeAndFlush("客户端信息处理Success!\r\n");}
}

服务端

public class AioServer extends Thread {private AsynchronousServerSocketChannel serverSocketChannel;@Overridepublic void run() {try {serverSocketChannel = AsynchronousServerSocketChannel.open(AsynchronousChannelGroup.withCachedThreadPool(Executors.newCachedThreadPool(), 10));serverSocketChannel.bind(new InetSocketAddress(7397));System.out.println("com.lm.netty01 aio server start done.  欢迎关注&获取源码}");// 等待CountDownLatch latch = new CountDownLatch(1);serverSocketChannel.accept(this, new AioServerChannelInitializer());latch.await();} catch (Exception e) {e.printStackTrace();}}public AsynchronousServerSocketChannel serverSocketChannel() {return serverSocketChannel;}public static void main(String[] args) {new AioServer().start();}
}

初始化

public class AioServerChannelInitializer extends ChannelInitializer {@Overrideprotected void initChannel(AsynchronousSocketChannel channel) throws Exception {channel.read(ByteBuffer.allocate(1024), 10, TimeUnit.SECONDS, null, new AioServerHandler(channel, Charset.forName("GBK")));}
}

处理消息

public class AioServerHandler extends ChannelAdapter {public AioServerHandler(AsynchronousSocketChannel channel, Charset charset) {super(channel, charset);}@Overridepublic void channelActive(ChannelHandler ctx) {try {System.out.println("码农明哥| 链接报告信息:" + ctx.channel().getRemoteAddress());//通知客户端链接建立成功ctx.writeAndFlush("码农明哥 | 通知服务端链接建立成功" + " " + new Date() + " " + ctx.channel().getRemoteAddress() + "\r\n");} catch (IOException e) {e.printStackTrace();}}@Overridepublic void channelInactive(ChannelHandler ctx) {}@Overridepublic void channelRead(ChannelHandler ctx, Object msg) {System.out.println("码农明哥 | 服务端收到:" + new Date() + " " + msg + "\r\n");ctx.writeAndFlush("服务端信息处理Success!\r\n");}
}

Channle适配器模仿Netty

public abstract class ChannelAdapter implements CompletionHandler<Integer, Object> {private AsynchronousSocketChannel channel;private Charset charset;public ChannelAdapter(AsynchronousSocketChannel channel, Charset charset) {this.channel = channel;this.charset = charset;if (channel.isOpen()) {channelActive(new ChannelHandler(channel, charset));}}@Overridepublic void completed(Integer result, Object attachment) {try {final ByteBuffer buffer = ByteBuffer.allocate(1024);final long timeout = 60 * 60L;channel.read(buffer, timeout, TimeUnit.SECONDS, null, new CompletionHandler<Integer, Object>() {@Overridepublic void completed(Integer result, Object attachment) {if (result == -1) {try {channelInactive(new ChannelHandler(channel, charset));channel.close();} catch (IOException e) {e.printStackTrace();}return;}buffer.flip();channelRead(new ChannelHandler(channel, charset), charset.decode(buffer));buffer.clear();channel.read(buffer, timeout, TimeUnit.SECONDS, null, this);}@Overridepublic void failed(Throwable exc, Object attachment) {exc.printStackTrace();}});} catch (Exception e) {e.printStackTrace();}}@Overridepublic void failed(Throwable exc, Object attachment) {exc.getStackTrace();}public abstract void channelActive(ChannelHandler ctx);public abstract void channelInactive(ChannelHandler ctx);// 读取消息抽象类public abstract void channelRead(ChannelHandler ctx, Object msg);}

服务端测试
启动服务端
在这里插入图片描述
在这里插入图片描述

BIO


目录结构如下
在这里插入图片描述

客户端


public class BioClient {public static void main(String[] args) {try {Socket socket = new Socket("192.168.2.178", 7397);System.out.println("itstack-demo-netty bio client start done. {关注公众号:bugstack虫洞栈 | 欢迎关注&获取源码}");BioClientHandler bioClientHandler = new BioClientHandler(socket, Charset.forName("utf-8"));bioClientHandler.start();} catch (IOException e) {e.printStackTrace();}}
}

消息处理器

public class BioClientHandler extends ChannelAdapter {public BioClientHandler(Socket socket, Charset charset) {super(socket, charset);}@Overridepublic void channelActive(ChannelHandler ctx) {System.out.println("链接报告LocalAddress:" + ctx.socket().getLocalAddress());ctx.writeAndFlush("hi! 我是码农明哥 BioClient to msg for you \r\n");}@Overridepublic void channelRead(ChannelHandler ctx, Object msg) {System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息:" + msg);ctx.writeAndFlush("hi 我已经收到你的消息Success!\r\n");}
}

服务端

public class BioServer extends Thread {private ServerSocket serverSocket = null;public static void main(String[] args) {BioServer bioServer = new BioServer();bioServer.start();}@Overridepublic void run() {try {serverSocket = new ServerSocket();serverSocket.bind(new InetSocketAddress(7397));System.out.println("com.lm.netty01.bio bio server start done. {关注码农明哥| 欢迎关注&获取源码}");while (true) {Socket socket = serverSocket.accept();BioServerHandler handler = new BioServerHandler(socket, Charset.forName("GBK"));handler.start();}} catch (IOException e) {e.printStackTrace();}}
}

消息处理器


public class BioServerHandler extends ChannelAdapter {public BioServerHandler(Socket socket, Charset charset) {super(socket, charset);}@Overridepublic void channelActive(ChannelHandler ctx) {System.out.println("链接报告LocalAddress:" + ctx.socket().getLocalAddress());ctx.writeAndFlush("hi! 我是码农明哥 BioServer to msg for you \r\n");}@Overridepublic void channelRead(ChannelHandler ctx, Object msg) {System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息:" + msg);ctx.writeAndFlush("hi 我已经收到你的消息Success!\r\n");}
}

适配器

public abstract class ChannelAdapter extends Thread {private Socket socket;private ChannelHandler channelHandler;private Charset charset;public ChannelAdapter(Socket socket, Charset charset) {this.socket = socket;this.charset = charset;while (!socket.isConnected()) {break;}channelHandler = new ChannelHandler(this.socket, charset);channelActive(channelHandler);}@Overridepublic void run() {try {BufferedReader input = new BufferedReader(new InputStreamReader(this.socket.getInputStream(), charset));String str = null;while ((str = input.readLine()) != null) {channelRead(channelHandler, str);}} catch (IOException e) {e.printStackTrace();}}// 链接通知抽象类public abstract void channelActive(ChannelHandler ctx);// 读取消息抽象类public abstract void channelRead(ChannelHandler ctx, Object msg);
}

BIO测试
启动服务端

在这里插入图片描述
在这里插入图片描述

NIO


目录结构如下
在这里插入图片描述
客户端

public class NioClient {public static void main(String[] args) throws IOException {Selector selector = Selector.open();SocketChannel socketChannel = SocketChannel.open();socketChannel.configureBlocking(false);boolean isConnect = socketChannel.connect(new InetSocketAddress("192.168.2.178", 7397));if (isConnect) {socketChannel.register(selector, SelectionKey.OP_READ);} else {socketChannel.register(selector, SelectionKey.OP_CONNECT);}System.out.println("com.lm.netty01.nio nio client start done. {关注码农明哥 | 欢迎关注&获取源码}");new NioClientHandler(selector, Charset.forName("GBK")).start();}
}

消息处理器

public class NioClientHandler  extends ChannelAdapter {public NioClientHandler(Selector selector, Charset charset) {super(selector, charset);}@Overridepublic void channelActive(ChannelHandler ctx) {try {System.out.println("链接报告LocalAddress:" + ctx.channel().getLocalAddress());ctx.writeAndFlush("hi! 我是,码农明哥 NioClient to msg for you \r\n");} catch (IOException e) {e.printStackTrace();}}@Overridepublic void channelRead(ChannelHandler ctx, Object msg) {System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息:" + msg);ctx.writeAndFlush("hi 我已经收到你的消息Success!\r\n");}
}

服务端

public class NioServer {private Selector selector;private ServerSocketChannel socketChannel;public static void main(String[] args) throws IOException {new NioServer().bind(7893);}public void bind(int port) {try {selector = Selector.open();socketChannel = ServerSocketChannel.open();socketChannel.configureBlocking(false);socketChannel.socket().bind(new InetSocketAddress(port), 1024);socketChannel.register(selector, SelectionKey.OP_ACCEPT);System.out.println("com.lm.netty01.nio server start done. {关注码农明哥 | 欢迎关注&获取源码}");new NioServerHandler(selector, Charset.forName("GBK")).start();} catch (IOException e) {e.printStackTrace();}}}

消息处理器

public class NioServerHandler extends ChannelAdapter {public NioServerHandler(Selector selector, Charset charset) {super(selector, charset);}@Overridepublic void channelActive(ChannelHandler ctx) {try {System.out.println("链接报告LocalAddress:" + ctx.channel().getLocalAddress());ctx.writeAndFlush("hi! 我是码农明哥 NioServer to msg for you \r\n");} catch (IOException e) {e.printStackTrace();}}@Overridepublic void channelRead(ChannelHandler ctx, Object msg) {System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息:" + msg);ctx.writeAndFlush("hi 我已经收到你的消息Success!\r\n");}}

Nio测试
启动NioServer
在这里插入图片描述
在这里插入图片描述
好了到这里就结束了基础的netty学习,大家一定要跟着动手操作起来。需要的源码的 可私信我获取;
重要:
给大家构建了个资源群 欢迎圈友携朋友一起加入 大家需要的si我进。

http://www.lryc.cn/news/454862.html

相关文章:

  • 在找工作吗?给你一个AI虚拟面试官助力你提前准备面试
  • @KafkaListener注解中containerFactory属性的作用
  • 1006C简单题(计数式子的组合意义 + dp式子联立)
  • 千益畅行,旅游创业新模式的创新与发展
  • 单调栈day54|42. 接雨水(高频面试题)、84. 柱状图中最大的矩形、两道题思维导图的汇总与对比
  • 关于Excel将列号由字母改为数字
  • 曾黎第二次受邀巴黎时装周看秀 为新疆棉代言引人瞩目
  • No.6 笔记 | Linux操作系统基础:全面概览与核心要点
  • MySQL之分库分表后带来的“副作用”你是怎么解决的?
  • 【Python】Python-JOSE:Python 中的 JSON Web Token 处理库
  • SpringBoot3+Druid YAML配置
  • 【c语言——指针详解(3)】
  • QT系统学习篇(2)- Qt跨平台GUI原理机制
  • 运用MinIO技术服务器实现文件上传——在Linux系统上安装和启动(一)
  • Python技术深度探索:从基础到进阶的实践之旅(第一篇)
  • 利士策分享,旅游是否要舟车劳顿才能尽兴?
  • C++入门——类的默认成员函数(取地址运算符重载)
  • 学习记录:js算法(四十九):二叉树的层序遍历
  • 【PCB工艺】表面贴装技术中常见错误
  • 3.使用条件语句编写存储过程(3/10)
  • Effective C++中文版学习记录(三)
  • VBA学习(76):文件合并神器/代码
  • 非农就业数据超预期,美联储降息步伐或放缓?
  • 每日OJ题_牛客_乒乓球筐_哈希_C++_Java
  • 基于SpringBoot+Vue的酒店客房管理系统
  • 检索增强思考 RAT(RAG+COT):提升 AI 推理能力的强大组合
  • python脚本实现Redis未授权访问漏洞利用
  • 简单线性回归分析-基于R语言
  • 上海理工大学《2023年+2019年867自动控制原理真题》 (完整版)
  • 计算机网络面试题——第三篇