首页 技术 正文
技术 2022年11月14日
0 收藏 965 点赞 2,372 浏览 1503 个字

Netty 源码 ChannelHandler(三)概述

Netty 系列目录(https://www.cnblogs.com/binarylei/p/10117436.html)

一、ChannelInboundHandler 和 ChannelOutboundHandler

Netty 中的事件分为 Inbound 事件和 Outbound 事件。

Inbound 事件通常由 IO 线程触发例如 TCP 链路建立事件、链路关闭事件、读事件、异常通知事件。触发 Inbound 事件的方法如下:

操作 说明
channelRegistered channel 注册到 eventLoop
channelUnregistered channel 取消注册
channelActive channel 连接
channelInactive channel 失连
channelRead
channelReadComplete 读完成
userEventTriggered 用户自定义事件
channelWritabilityChanged 写状态改变??
exceptionCaught 异常

Outbound 事件通常是由用户主动发起的网络 IO 操作,例如用户发起的连接操作、绑定操作、消息发送等操作。

操作 说明
bind 绑定端口
connect 连接
disconnect 断开连接
close 关闭 channel
read
write
flush 刷新
deregister channel 取消注册

二、ChannelHandler 功能说明

2.1 ByteToMessageDecoder 和 MessageToByteEncoder

将读取到的字节数组或者字节缓冲区解码为业务可以使用的 POJO 对象。为了方便业务将 Bytebuf 解码成业务 POJO 对象,Netty 提供了 ByteToMessageDecoder 抽象工具解码类。

public MyByteToMessageDecoder extends ByteToMessageDecoder {
public void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
}
}

注意: ByteToMessageDecoder 并没有考虑 TCP 粘包和组包等场景,读半包需要用户解码器自己负责处理。

MessageToByteEncoder 则相反将 POJO 对象编码成 ByteBuf:

public MyMessageToByteEncoder extends MessageToByteEncoder {
public void encode(ChannelHandlerContext ctx, I msg, ByteBuf out) throws Exception {
}
}

2.2 MessageToMessageDecoder 和 MessageToMessageEncoder

将一个 POJO 对象编码成另一个对象,以 HTTP + XML 协议为例,它的一种实现方式是:先将 POJO 对象编码成 XML 字符串,再将字符串编码为 HTTP 请求或者应答消息。对于复杂协议,往往需要经历多次编码,为了便于功能扩展,可以通过多个编码器组合来完成。

public MyMessageToMessageDecoder extends MessageToMessageDecoder {
public void decode(ChannelHandlerContext ctx, I msg, List<Object> out) {
}
}

2.3 LengthFieldBasedFrameDecoder 和 LengthFieldPrepender


每天用心记录一点点。内容也许不重要,但习惯很重要!

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:9,497
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,910
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,744
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,498
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:8,136
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:5,300