Netty自定义编码解码器

上次通信的时候用的是自带的编解码器,今天自己实现一下自定义的。
1、自定义一下协议

//协议类
@Data
public class Protocol<T> implements Serializable {private Long id = System.currentTimeMillis();private short msgType;// 假设1为请求 2为响应private T body;}//消息请求体
@Data
public class RequestMsg implements Serializable {private String msg;private String other;}//消息响应体
@Data
public class ResponseMsg implements Serializable {private String result;private String error;}

2、定义编解码器import io.netty.buffer.ByteBuf;

import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;//编码器
public class EnCodeMsg extends MessageToByteEncoder<Protocol<Object>> {@Overrideprotected void encode(ChannelHandlerContext channelHandlerContext, Protocol<Object> msg, ByteBuf byteBuf) throws Exception {Serialization serialization = new JdkSerialization();byte[] body = serialization.serialize(msg.getBody());int length = body.length;Long id = msg.getId();short msgType = msg.getMsgType();byteBuf.writeLong(id);byteBuf.writeShort(msgType);byteBuf.writeInt(length);byteBuf.writeBytes(body);}
}import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;import java.util.List;//解码器
public class DeCodeMsg extends ByteToMessageDecoder {@Overrideprotected void decode(ChannelHandlerContext channelHandlerContext, ByteBuf in, List<Object> list) throws Exception {Serialization serialization = new JdkSerialization();long id = in.readLong();short msgType = in.readShort();int bodyLength = in.readInt();int i = in.readableBytes();if(bodyLength!=i){in.resetReaderIndex();return;}byte[] bytes = new byte[bodyLength];in.readBytes(bytes);if(msgType==(short)1){Protocol<RequestMsg> requestMsgProtocol = new Protocol<>();RequestMsg requestMsg = serialization.deserialize(bytes, RequestMsg.class);requestMsgProtocol.setBody(requestMsg);requestMsgProtocol.setId(id);requestMsgProtocol.setMsgType(msgType);list.add(requestMsgProtocol);}else if(msgType==(short)2){Protocol<ResponseMsg> responseMsgProtocol = new Protocol<>();ResponseMsg responseMsg = serialization.deserialize(bytes,ResponseMsg.class);responseMsgProtocol.setId(id);responseMsgProtocol.setMsgType(msgType);responseMsgProtocol.setBody(responseMsg);list.add(responseMsgProtocol);}else {return;}}
}

3、修改消息处理器


public class NettyClientHandler extends SimpleChannelInboundHandler<Protocol<ResponseMsg>> {private static final Logger logger = LoggerFactory.getLogger(NettyClientHandler.class);private volatile Channel channel;private SocketAddress remotePeer;public Channel getChannel() {return channel;}public SocketAddress getRemotePeer() {return remotePeer;}/*** 注册* @param ctx* @throws Exception*/@Overridepublic void channelRegistered(ChannelHandlerContext ctx) throws Exception {logger.info("channelRegistered--------------");super.channelRegistered(ctx);this.channel = ctx.channel();}/*** 激活* @param ctx* @throws Exception*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {super.channelActive(ctx);this.remotePeer = this.channel.remoteAddress();logger.info("channelActive--------------");}@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext,Protocol<ResponseMsg> o) throws Exception {logger.info("channelRead0--------------"+Thread.currentThread().getName());logger.info("消费者接收到的消息为{}", JSONObject.toJSONString(o));}public void sendMsg(Protocol<RequestMsg> message){channel.writeAndFlush(message);}public void close(){channel.writeAndFlush(Unpooled.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);}}
public class NettyServerHandler extends SimpleChannelInboundHandler<Protocol<RequestMsg>> {private static final Logger logger = LoggerFactory.getLogger(NettyServerHandler.class);@Overrideprotected void channelRead0(ChannelHandlerContext channelHandlerContext, Protocol<RequestMsg> o) throws Exception {logger.info("服务端收到的消息为================{}", JSONObject.toJSONString(o));Protocol<ResponseMsg> protocol = new Protocol<>();ResponseMsg responseMsg = new ResponseMsg();responseMsg.setResult("SUCCESS");responseMsg.setError("NO ERROR");protocol.setBody(responseMsg);protocol.setMsgType((short) 2);protocol.setId(o.getId());channelHandlerContext.channel().writeAndFlush(protocol);}
}

4、测试

public class NettyTest {public static void main(String[] args) {new Thread(()->{NettyServer.startNettyServer();}).start();new Thread(()->{NettyClient instance = NettyClient.getInstance();try {while (true){Thread.sleep(2000);Protocol<RequestMsg> protocol = new Protocol<>();protocol.setMsgType((short)1);RequestMsg requestMsg = new RequestMsg();requestMsg.setMsg("hello:"+System.currentTimeMillis());requestMsg.setOther("你好啊");protocol.setBody(requestMsg);instance.sendMsg(protocol);}} catch (Exception e) {e.printStackTrace();}}).start();}
}

5、效果截图

在这里插入图片描述

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

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

相关文章

数据结构---跳表

目录标题 为什么会有跳表跳表的原理跳表的模拟实现准备工作find函数insert函数erase函数 测试效率比较 为什么会有跳表 在前面的学习过程中我们学习过链表这个容器&#xff0c;这个容器在头部和尾部插入数据的时间复杂度为O(1)&#xff0c;但是该容器存在一个缺陷就是不管数据…

【算法|数组】手撕经典二分法

算法|数组——二分查找 文章目录 算法|数组——二分查找引言二分查找左闭右闭写法左闭右开写法 总结 引言 首先学习这个算法之前需要了解数组知识&#xff1a;数组。 大概介绍以下&#xff1a; 数组是存储在连续内存空间上的相同类型数据的集合。数组下标都是从0开始。数组在…

第17章-Spring AOP经典应用场景

文章目录 一、日志处理二、事务控制三、参数校验四、自定义注解五、AOP 方法失效问题1. ApplicationContext2. AopContext3. 注入自身 六、附录1. 示例代码 AOP 提供了一种面向切面操作的扩展机制&#xff0c;通常这些操作是与业务无关的&#xff0c;在实际应用中&#xff0c;可…

2.虚拟机开启kali_linux

首先你应该搞一个虚拟机&#xff0c;搞虚拟机可以看一下这个 附录三 虚拟机的使用_Suyuoa的博客-CSDN博客 然后你需要搞一个 kali linux的镜像 Get Kali | Kali Linux 镜像下载好之后解压&#xff0c;你会得到一个文件夹包含下面这些文件 之后打开VMware&#xff0c;点击打开虚…

SpringBoot配置多数据源

一、pom依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId> </dependency><dependency><groupId>com.alibaba</groupId><artifactId>druid-spring…

企业如何挑选适合自己需求的文件传输软件

随着科技的日新月异&#xff0c;文件传输已成为我们生活中不可或缺的一部分。无论是在工作场合还是在日常生活中&#xff0c;我们经常需要传输各种格式和大小的文件&#xff0c;如文档、照片、音频和视频等。然而&#xff0c;在选择适合自己需求的文件传输软件时&#xff0c;很…

简化AD管理减少IT工作负担

管理和保护混合 AD 环境 IT 管理员几乎每天都要创建和管理多个 AD 对象&#xff0c;利用本机AD工具&#xff08;如Active Directory用户和计算机控制台以及PowerShell脚本&#xff09;来执行这些任务并不理想&#xff0c;因为它们必须在多个控制台之间切换才能执行这些任务&am…

【Java从入门到大牛】File和IO流上篇

&#x1f525; 本文由 程序喵正在路上 原创&#xff0c;CSDN首发&#xff01; &#x1f496; 系列专栏&#xff1a;Java从入门到大牛 &#x1f320; 首发时间&#xff1a;2023年8月9日 &#x1f98b; 欢迎关注&#x1f5b1;点赞&#x1f44d;收藏&#x1f31f;留言&#x1f43e…

Easys Excel的表格导入(读)导出(写)-----java

一,EasyExcel官网: 可以学习一些新知识: EasyExcel官方文档 - 基于Java的Excel处理工具 | Easy Excel 二,为什么要使用easyexcle excel的一些优点和缺点 java解析excel的框架有很多 &#xff1a; poi jxl,存在问题&#xff1a;非常的消耗内存&#xff0c; easyexcel 我们…

Llama 2 with langchain项目详解(一)

Llama 2 with langchain项目详解(一) 2023年2月25日,美国Meta公司发布了Llama 1开源大模型。随后,于2023年7月18日,Meta公司发布了Llama 2开源大模型,该系列包括了70亿、130亿和700亿等不同参数规模的模型。相较于Llama 1,Llama 2的训练数据增加了40%,上下文长度提升至…

Arduino 项目笔记 | Arduino LED Memory Game 颜色记忆游戏机

成果展示 颜色记忆游戏机 &#xff5c; Arduino DIY 1. 线路链连接 1.1 原理图 1.2 PCB 免费PCB打样 Arduino LED Memory Game 颜色记忆机资料下载 1.3 烧录 Bootloader 第二部分&#xff1a;Burn bootloader 2. 程序实现 #define NOTE_B0 31 #define NOTE_C1 33 #define NOT…

JMeter启动时常见的错误

很多小伙伴在学工具这一块时&#xff0c;安装也是很吃力的一个问题&#xff0c;之前记得有说过怎么安装jmeter这个工具。那么你要启动jmeter的时候&#xff0c;一些粉丝就会碰到如下几个问题。 1.解压下载好的jmeter安装&#xff0c;Windows 平台&#xff0c;双击 jmeter/bin …