物联网 基于netty编解码器机制与自定义协议

物联网 基于netty编解码器机制与自定义协议

编解码器

Netty 中网络传输的数据本质是 字节(ByteBuf),而业务逻辑通常操作 对象(如 POJO、字符串、JSON)

复制代码
编码器(Encoder):将业务对象 → 字节,以便写出到网络
解码器(Decoder):将字节 → 业务对象,以便业务 Handler 处理
TCP 流式特性带来的粘包/拆包问题,必须在 解码阶段 解决
Netty 提供了丰富的解码器基类,其中最重要的就是 ByteToMessageDecoder

源码(netty-sample-00-codec)

https://gitee.com/kcnf-iot/iot-sample/tree/master/netty/netty-sample-00

核心编解码器类层次

抽象类 作用
ByteToMessageDecoder 将入站字节解码为多个对象(可解决粘包/拆包)。需要实现 decode() 方法,将累积的字节解码成业务对象并放入
MessageToByteEncoder 将出站对象编码为字节。实现 encode() 方法。
ReplayingDecoder ByteToMessageDecoder 的子类,它通过状态机简化了解码逻辑,但性能略低(使用方便的断言方式)。
MessageToMessageDecoder 将一种消息类型解码为另一种(如 JSON 字符串 → POJO)。

协议格式

复制代码
+----------+----------------+
| 长度(4B) |   数据(变长)    |
+----------+----------------+

代码

server 端
复制代码
package com.jysemel.iot;

import com.jysemel.iot.code.CustomProtocolDecoder;
import com.jysemel.iot.code.CustomProtocolEncoder;
import com.jysemel.iot.handler.ServerBusinessHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class CustomProtocolServer {
    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            // 添加自定义解码器(解决粘包/拆包)
                            pipeline.addLast(new CustomProtocolDecoder());
                            // 添加自定义编码器(用于回显)
                            pipeline.addLast(new CustomProtocolEncoder());
                            // 业务 Handler
                            pipeline.addLast(new ServerBusinessHandler());
                        }
                    });
            ChannelFuture future = bootstrap.bind(8182).sync();
            System.out.println("自定义协议服务器启动,端口 8182");
            future.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
client 端
复制代码
package com.jysemel.iot;

import com.jysemel.iot.code.CustomProtocolDecoder;
import com.jysemel.iot.code.CustomProtocolEncoder;
import com.jysemel.iot.handler.ClientBusinessHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class CustomProtocolClient {

    public static void main(String[] args) throws InterruptedException {
        EventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new CustomProtocolDecoder());
                            pipeline.addLast(new CustomProtocolEncoder());
                            pipeline.addLast(new ClientBusinessHandler());
                        }
                    });
            ChannelFuture future = bootstrap.connect("127.0.0.1", 8182).sync();
            future.channel().closeFuture().sync();
        } finally {
            group.shutdownGracefully();
        }
    }
}
相关推荐
白搞电子8 小时前
ESP32-S31 上做可在线安装的 WASM 应用平台:0.4.9 Beta 发布
单片机·嵌入式硬件·物联网
microrain8 小时前
先应答,再入库:SagooIoT 接入 GB/T 32960 的四层宿主改造
物联网·golang·开源·sagooiot
智鸟科技GemeOpen开发者智能设备14 小时前
MQTT智能通断器GSCW1M2P · 开发者实战指南
开发语言·物联网·智能家居
智鸟科技GemeOpen开发者智能设备16 小时前
平安校园 AI 智能实时告警系统 智鸟科技·GemeOpen + 谷华科技·融合创新方案白皮书
java·开发语言·python·物联网·智能家居
悟天特斯16 小时前
数字孪生的“虚实融合“:让园区模型从“看得见“到“用得好“
大数据·人工智能·物联网
常州晟凯电子科技18 小时前
sigmaStar SSC305DE/SSC308开发笔记之开发环境搭建和SDK编译
人工智能·笔记·嵌入式硬件·物联网·性能优化·视频编解码
Zhao136824553911 天前
国产替代DPE5500百兆以太网控制芯片兼容W5500
嵌入式硬件·物联网
microrain2 天前
同一个寄存器,四种读法:SagooIoT Modbus 驱动的字节序、宽度与功能码
物联网·golang·开源·sagooiot
智圣新创012 天前
教育数据要素流通刚需下 智圣新创高校数据中台解决方案的全域建设落地框架
大数据·人工智能·物联网
DS小龙哥2 天前
从呼吸心率到离床报警:60G雷达睡眠仪全栈开发实录(硬件+MQTT+小程序)DIY一台全功能睡眠监护仪
stm32·单片机·嵌入式硬件·物联网·小程序·智能家居