Day472&473&474.Netty 核心模块组件 -netty
Posted 阿昌喜欢吃黄桃
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Day472&473&474.Netty 核心模块组件 -netty相关的知识,希望对你有一定的参考价值。
Netty 核心模块组件
一、Bootstrap、ServerBootstrap
-
Bootstrap 意思是引导,一个 Netty 应用通常由一个 Bootstrap 开始,主要作用是配置整个 Netty 程序,串联各个组件Netty 中 :
Bootstrap
类是客户端
程序的启动引导类ServerBootstrap
是服务端
启动引导类
-
常见的方法
- public ServerBootstrap group(EventLoopGroup parentGroup, EventLoopGroup childGroup),该方法用于服务器端,用来设置两个 EventLoop
- public B group(EventLoopGroup group) ,该方法用于客户端,用来设置一个 EventLoop
- public B channel(Class<? extends C> channelClass),该方法用来设置一个服务器端的通道实现
- public < T > B option(ChannelOption option, T value),用来给 ServerChannel 添加配置
- public < T > ServerBootstrap childOption(ChannelOption childOption, T value),用来给接收到的通道添加配置
- public ServerBootstrap childHandler(ChannelHandler childHandler),该方法用来设置业务处理类(自定义的handler)针对WorkerGroup(干活的类)
- public ServerBootstrap handler(ChannelHandler handler)针对BoosGroup(专门负责接收客户端请求的类)
- public ChannelFuture bind(int inetPort) ,该方法用于服务器端,用来设置占用的端口号
- public ChannelFuture connect(String inetHost, int inetPort) ,该方法用于客户端,用来连接服务器端
二、Future、ChannelFuture
Netty 中所有的 IO 操作都是异步
的,不能立刻得知消息是否被正确处理。
但是可以过一会等它执行完成或者直接注册一个监听,具体的实现就是通过 Future 和 ChannelFutures,他们可以注册一个监听,当操作执行成功或失败时监听会自动触发注册的监听事件
- 常见的方法
- Channel channel(),返回当前正在进行 IO 操作的通道
- ChannelFuture sync(),等待异步操作执行完毕
三、Channel
-
Netty 网络通信的组件,能够用于执行网络 I/O 操作。
-
通过 Channel 可获得当前网络连接的
通道的状态
-
通过 Channel 可获得
网络连接的配置参数
(例如接收缓冲区大小) -
Channel 提供异步的网络 I/O 操作(如建立连接,读写,绑定端口),异步调用意味着任何 I/O 调用都将立即返回,并且不保证在调用结束时所请求的 I/O 操作已完成
-
调用立即返回一个 ChannelFuture 实例,
通过注册监听器
到 ChannelFuture 上,可以 I/O 操作成功、失败或取消时回调通知调用方 -
支持关联 I/O 操作与对应的处理程序
-
不同协议、不同的阻塞类型的连接都有不同的 Channel 类型与之对应,常用的 Channel 类型:
- NiosocketChannel,异步的客户端 TCP Socket 连接。
- NioServerSocketChannel,异步的服务器端 TCP Socket 连接。
- NioDatagramChannel,异步的 UDP 连接。
- NioSctpChannel,异步的客户端 Sctp 连接。
- NioSctpServerChannel,异步的 Sctp 服务器端连接,这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO。
四、Selector
- Netty 基于
Selector 对象实现 I/O 多路复用
,通过Selector 一个线程可以监听多个连接的 Channel 事件
。 - 当向一个 Selector 中注册 Channel 后,Selector 内部的机制就可以
自动不断地查询(Select) 这些注册的Channel 是否有已就绪的 I/O 事件
(例如可读,可写,网络连接完成等),这样程序就可以很简单地使用一个线程高效地管理多个 Channel
五、ChannelHandler 及其实现类
- ChannelHandler 是一个接口,处理 I/O 事件或拦截 I/O 操作,并将其转发到其 ChannelPipeline(业务处理链)中的下一个处理程序。
- ChannelHandler 本身并没有提供很多方法,因为这个接口有许多的方法需要实现,方便使用期间,可以继承它的子类
- ChannelHandler 及其实现类一览图
- 我们经常需要自定义一个 Handler 类去继承 ChannelInboundHandlerAdapter
- 然后通过重写相应方法实现业务逻辑,我们接下来看看一般都需要重写哪些方法
六、Pipeline 和 ChannelPipeline
-
ChannelPipeline 是一个重点:
-
ChannelPipeline 是一个
Handler 的集合
-
它负责处理和拦截 inbound 或者 outbound 的事件和操作,相当于一个贯穿 Netty 的链。(也可以这样理解:
ChannelPipeline 是 保存 ChannelHandler 的 List,用于处理或拦截Channel 的入站事件和出站操作)
-
ChannelPipeline 实现了一种高级形式的拦截过滤器模式,使用户可以完全控制事件的处理方式,以及 Channel中各个的 ChannelHandler 如何相互交互
-
在 Netty 中每个 Channel 都有且仅有一个 ChannelPipeline 与之对应,它们的组成关系如下
-
- channel能拿到他对应的channelPipeline
- channelPipeline也可以获取到对应的channel
- channelPipeline中包含一个个的ChannelHandlerContext的双向链表
- 每个ChannelHandlerContext(
保存 Channel 相关的所有上下文信息
)里面包含对应具体的channelHandler
-
常用方法
-
ChannelPipeline addFirst(ChannelHandler… handlers)
把一个业务处理类(handler)添加到链中的第一个位置
-
ChannelPipeline addLast(ChannelHandler… handlers)
把一个业务处理类(handler)添加到链中的最后一个位置
-
七、ChannelHandlerContext
-
保存 Channel 相关的所有上下文信息,同时关联一个 ChannelHandler 对象
-
即 ChannelHandlerContext 中 包 含 一 个 具 体 的 事 件 处 理 器 ChannelHandler , 同 时ChannelHandlerContext 中也绑定了对应的 pipeline 和 Channel 的信息,方便对 ChannelHandler 进行调用.
-
常用方法
八、ChannelOption
-
Netty 在创建 Channel 实例后,一般都需要设置 ChannelOption 参数。
-
ChannelOption 参数
如下:
九、EventLoopGroup 和其实现类 NioEventLoopGroup
-
EventLoopGroup 是一组
EventLoop(就是对应线程)
的抽象,Netty 为了更好的利用多核 CPU 资源,一般会有多个 EventLoop同时工作,每个 EventLoop 维护着一个 Selector 实例。 -
EventLoopGroup 提供 next 接口,可以从组里面按照一定规则获取其中一个 EventLoop 来处理任务。
-
在 Netty服务器端编程中 ,我们一般 都 需 要 提 供 两 个 EventLoopGroup , 例 如 :
- BossEventLoopGroup
- WorkerEventLoopGroup
-
通常一个服务端口即一个 ServerSocketChannel 对应一个 Selector 和一个 EventLoop 线程。
-
服务端中,BossEventLoop 负责接收客户端的连接并将 SocketChannel 交给 WorkerEventLoopGroup 来进行 IO 处理,如下图所示:↓
-
常用方法:
-
public NioEventLoopGroup(),构造方法
-
public Future<?> shutdownGracefully(),断开连接,关闭线程
-
十、 Unpooled 类
-
Netty 提供一个
专门用来操作缓冲区
(即 Netty 的数据容器)的工具类
-
他内部维护了对应的
readerIndex
和writerIndex
-
相比NIO的ByteBuffer,Netty 提供的ByteBuf不用考虑flip反转去操作读写
-
常用方法如下所示
-
举例说明 Unpooled 获取 Netty 的数据容器 ByteBuf 的基本使用
-
案例1
public class NettyByteBuf01 public static void main(String[] args) //创建一个 ByteBuf //说明 //1. 创建 对象,该对象包含一个数组 arr , 是一个 byte[10] //2. 在 netty 的 buffer 中,不需要使用 flip 进行反转 // 底层维护了 readerindex 和 writerIndex //3. 通过 readerindex 和 writerIndex 和 capacity, 将 buffer 分成三个区域 // 0---readerindex 已经读取的区域 // readerindex---writerIndex , 可读的区域 // writerIndex -- capacity, 可写的区域 ByteBuf buffer = Unpooled.buffer(10); for(int i = 0; i < 10; i++) buffer.writeByte(i); System.out.println("capacity=" + buffer.capacity());//10 //输出 // for(int i = 0; i<buffer.capacity(); i++) // System.out.println(buffer.getByte(i)); // for(int i = 0; i < buffer.capacity(); i++) System.out.println(buffer.readByte()); System.out.println("执行完毕");
-
案例 2
public class NettyByteBuf02 public static void main(String[] args) //创建 ByteBuf ByteBuf byteBuf = Unpooled.copiedBuffer("hello,world!", Charset.forName("utf-8")); //使用相关的方法 if(byteBuf.hasArray()) // true byte[] content = byteBuf.array(); //将 content 转成字符串 System.out.println(new String(content, Charset.forName("utf-8"))); System.out.println("byteBuf=" + byteBuf); System.out.println(byteBuf.arrayOffset()); // 0 System.out.println(byteBuf.readerIndex()); // 0 System.out.println(byteBuf.writerIndex()); // 12 System.out.println(byteBuf.capacity()); // 36 //System.out.println(byteBuf.readByte()); // System.out.println(byteBuf.getByte(0)); // 104 int len = byteBuf.readableBytes(); //可读的字节数 12 System.out.println("len=" + len); //使用 for 取出各个字节 for(int i = 0; i < len; i++) System.out.println((char) byteBuf.getByte(i)); //按照某个范围读取 System.out.println(byteBuf.getCharSequence(0, 4, Charset.forName("utf-8"))); System.out.println(byteBuf.getCharSequence(4, 6, Charset.forName("utf-8")));
-
十一、Netty 应用实例-群聊系统
- 实例要求
- 编写一个 Netty 群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
- 实现多人群聊
- 服务器端:可以监测用户上线,离线,并实现消息转发功能
- 客户端:通过 channel 可以无阻塞发送消息给其它所有用户,同时可以接受其它用户发送的消息(有服务器转发得到)
- 目的:进一步理解 Netty 非阻塞网络编程机制
- 服务端
GroupChatServerHandler 服务端处理器
/******
@author 阿昌
@create 2021-12-09 20:52
*******
* 自定义服务器处理器
*/
public class GroupChatServerHandler extends SimpleChannelInboundHandler<String>
//定义管理每个客户端的channel组
//GlobalEventExecutor.INSTANCE 全局的事件执行器,他是单例的
private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//当连接建立会第一个执行该方法,【客户端连接事件】
@Override
public void handlerAdded(ChannelHandlerContext ctx) throws Exception
//当客户端连接,第一时间将每个客户端的channel加入到channelGroup统一管理
Channel channel = ctx.channel();
//给当前channelGroup管理的所有channel的客户端都发送消息
channelGroup.writeAndFlush(sdf.format(new Date()) + "[客户端]" + channel.remoteAddress() + "加入聊天室...");
channelGroup.add(channel);
//当某个channel处于活动状态,就会触发,用于发送某某上线【客户端上线活动状态事件】
@Override
public void channelActive(ChannelHandlerContext ctx) throws Exception
Channel channel = ctx.channel();
System.out.println(sdf.format(new Date()) + "[客户端上线]:" + channel.remoteAddress() + "");//打印给服务端看
//当某个channel离开状态,就会触发,用于发送某某下线【客户端离开非活动状态事件】
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception
channelGroup.writeAndFlush(sdf.format(new Date()) + "[客户端]" + ctx.channel().remoteAddress() + "离线了...");
//当某个channel断开连接状态,就会触发【客户端离线断开连接事件】
@Override
public void handlerRemoved(ChannelHandlerContext ctx) throws Exception
//告诉当前所有在线的用户,某某某断开连接
Channel channel = ctx.channel();
channelGroup.writeAndFlush(sdf.format(new Date()) + "[客户端]" + channel.remoteAddress() + "离开聊天室...");
System.out.println("当前channel组的个数为:" + channelGroup.size());
//客户端发送消息会触发【读取客户端数据事件】
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception
//获取当前发送消息的用户
Channel nowSendChannel = ctx.channel();
//排除发送者自己,不给他转发消息
for (Channel channel : channelGroup)
if (!channel.equals(nowSendChannel))
channel.writeAndFlush(sdf.format(new Date()) + "[客户_" + channel.remoteAddress() + "]发言:" + msg + "");//别的客户端
else
channel.writeAndFlush(sdf.format(new Date()) + "[您自己发送的消息为]:" + msg + "");//发送者自己,回显消息给自己看
//当发生异常会触发【异常触发事件】
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
Channel channel = ctx.channel();
channel.close();//关闭通道
GroupChatServer 服务端启动
/******
@author 阿昌
@create 2021-12-09 20:40
*******
* 群聊系统服务端
*/
public class GroupChatServer
private final Integer port;//监听端口
private GroupChatServer (Integer port)
this.port=port;
public void run() throws InterruptedException
//创建两个线程组
NioEventLoopGroup boosGroup = new NioEventLoopGroup(1);
NioEventLoopGroup workGroup = new NioEventLoopGroup(8);
try
ServerBootstrap serverBootstrap = new ServerBootstrap();
serverBootstrap.group(boosGroup,workGroup)
.channel(NioServerSocketChannel.class)
.option(ChannelOption.SO_BACKLOG,128)
.childOption(ChannelOption.SO_KEEPALIVE,true)
.childHandler(new ChannelInitializer<SocketChannel>()
protected void initChannel(SocketChannel ch) throws Exception
ChannelPipeline pipeline = ch.pipeline();
//向pipeline加入处理器
pipeline.addLast("decoder",new StringDecoder());//解码器
//如果不加这个编码解码器的 无法直接传输字符串
pipeline.addLast("encoder",new StringEncoder());//编码器
pipeline.addLast("MyHandler",new GroupChatServerHandler());//自己的业务处理器
);
System.out.println("netty服务器启动成功.....绑定端口:"+port);
ChannelFuture cf = serverBootstrap.bind(port).sync();
cf.channel().closeFuture().sync();//监听关闭时间
finally
boosGroup.shutdownGracefully();
workGroup.shutdownGracefully();
//主入口
public static void main(String[] args) throws InterruptedException
GroupChatServer server = new GroupChatServer(7000);
server.run();
- 客户端
GroupChatClientHandler 客户端处理器
/******
@author 阿昌
@create 2021-12-09 21:31
*******
* 聊天室客户端处理器
*/
public class GroupChatClientHandler extends SimpleChannelInboundHandler<String>
//读取服务端发来的消息【读写消息事件】
protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception
Channel channel = ctx.channel();
System.out.println("[用户_"+channel.remoteAddress()+"]发送的消息为:"+msg);
GroupChatClient 客户端启动
/******
@author 阿昌
@create 2021-12-09 21:20
*******
* 群聊系统客户端
*/
public class GroupChatClient
private final String ipaddr;
private final int port;
private GroupChatClient(String ipaddr,int port) throws InterruptedException
this.ipaddr = ipaddr;
this.port = port;
private void run() throws InterruptedException
NioEventLoopGroup clientGroup = new NioEventLoopGroup();
try
Bootstrap clientBootstrap = new Bootstrap();
clientBootstrap.group(clientGroup)
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<SocketChannel>()
protected void initChannel(SocketChannel ch) throws Exception
ChannelPipeline pipeline =以上是关于Day472&473&474.Netty 核心模块组件 -netty的主要内容,如果未能解决你的问题,请参考以下文章