netty编程之自定义编解码器

2024-08-24 00:04

本文主要是介绍netty编程之自定义编解码器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

写在前面

源码 。
本文看下netty如何自定义编解码器。为此netty专门定义抽象类io.netty.handler.codec.MessageToByteEncoderio.netty.handler.codec.ByteToMessageDecoder,后续我们实现自定义的编解码器就继承这两个类来做。

1:正戏

server 启动类:

package com.dahuyou.netty.customercodec.server;import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;public class NettyServer {public static void main(String[] args) {new NettyServer().bing(7397);}private void bing(int port) {//配置服务端NIO线程组EventLoopGroup parentGroup = new NioEventLoopGroup(); //NioEventLoopGroup extends MultithreadEventLoopGroup Math.max(1, SystemPropertyUtil.getInt("io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));EventLoopGroup childGroup = new NioEventLoopGroup();try {ServerBootstrap b = new ServerBootstrap();b.group(parentGroup, childGroup).channel(NioServerSocketChannel.class)    //非阻塞模式.option(ChannelOption.SO_BACKLOG, 128).childHandler(new MyChannelInitializer());ChannelFuture f = b.bind(port).sync();f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {childGroup.shutdownGracefully();parentGroup.shutdownGracefully();}}}

MyChannelInitializer类:

package com.dahuyou.netty.customercodec.server;import com.dahuyou.netty.customercodec.codec.MyDecoder;
import com.dahuyou.netty.customercodec.codec.MyEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;public class MyChannelInitializer extends ChannelInitializer<SocketChannel> {@Overrideprotected void initChannel(SocketChannel channel) {
/**/
/*System.out.println("远端连接初始化,IP:" + channel.remoteAddress().getHostString() + ", port:" + channel.remoteAddress().getPort());*//**/
/* 解码器 *//*// 基于换行符号,基于换行符来分割字符串???
//        channel.pipeline().addLast(new LineBasedFrameDecoder(1024));// 基于指定字符串【换行符,这样功能等同于LineBasedFrameDecoder】// e.pipeline().addLast(new DelimiterBasedFrameDecoder(1024, false, Delimiters.lineDelimiter()));// 基于最大长度// e.pipeline().addLast(new FixedLengthFrameDecoder(4));// 解码转String,注意调整自己的编码格式GBK、UTF-8 byte->stringchannel.pipeline().addLast(new StringDecoder(Charset.forName("GBK")));// 增加内置编码器,这样向对端发送消息就不要转换为二进制数据了channel.pipeline().addLast(new StringEncoder(Charset.forName("GBK")));//在管道中添加我们自己的接收数据实现方法channel.pipeline().addLast(new MyServerHandler());
\*/// 这里我们就不使用string的decoder和encoder了,而是使用自定义的编解码器// 解码器对应的抽象类是:ByteToMessageDecoder// 编码器对应的抽象类是:MessageToByteEncoder//自定义解码器channel.pipeline().addLast(new MyDecoder());//自定义编码器channel.pipeline().addLast(new MyEncoder());//在管道中添加我们自己的接收数据实现方法channel.pipeline().addLast(new MyServerHandler());}}

其中的MyDecoder,MyEncoder就是需要我们自己的定义了编解码器了,如下:

package com.dahuyou.netty.customercodec.codec;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import java.nio.charset.Charset;
import java.util.List;/*** 自定义的解码器*/
//public class MyDecoder extends ByteToMessageDecoder<String> {
public class MyDecoder extends ByteToMessageDecoder {int BASE_LENGTH = 4;/*一个完整包的开始标记*/private final byte START_LABEL = 0x02;/*一个完整包的结束标记*/private final byte END_LABEL = 0x03;@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {//基础长度不足,我们设定基础长度为4if (in.readableBytes() < BASE_LENGTH) {return;}int beginIdx; //记录包头位置while (true) {// 获取包头开始的indexbeginIdx = in.readerIndex();// 标记包头开始的indexin.markReaderIndex();// 读到了协议的开始标志,结束while循环
//            if (in.readByte() == 0x02) {if (in.readByte() == START_LABEL) {break;}// 未读到包头,略过一个字节// 每次略过,一个字节,去读取,包头信息的开始标记in.resetReaderIndex();in.readByte();// 当略过,一个字节之后,// 数据包的长度,又变得不满足// 此时,应该结束。等待后面的数据到达if (in.readableBytes() < BASE_LENGTH) {return;}}//剩余长度不足可读取数量[没有内容长度位]int readableCount = in.readableBytes();if (readableCount <= 1) {in.readerIndex(beginIdx);return;}//长度域占4字节,读取intByteBuf byteBuf = in.readBytes(1);String msgLengthStr = byteBuf.toString(Charset.forName("GBK"));int msgLength = Integer.parseInt(msgLengthStr);//剩余长度不足可读取数量[没有结尾标识]readableCount = in.readableBytes();if (readableCount < msgLength + 1) {in.readerIndex(beginIdx);return;}ByteBuf msgContent = in.readBytes(msgLength);//如果没有结尾标识,还原指针位置[其他标识结尾]byte end = in.readByte();
//        if (end != 0x03) {if (end != END_LABEL) {in.readerIndex(beginIdx);return;}out.add(msgContent.toString(Charset.forName("GBK")));}
/*@Overrideprotected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {}*/
}

解码器定义了这样的规则,ASCII码02作为开始字符,ASCII码03作为结束字符,这两个字符都是不可见的控制字符,分别是STX(start of text),ETX(end of text),如下是对stx比较专业的描述:

STX 是 ASCII(American Standard Code for Information Interchange,美国信息交换标准代码)中定义的一个控制字符,其代表“Start of Text”,即正文开始。在数据传输或文本通信中,STX 字符用于标记一个结构化数据块(如纯文本消息)的起始点。它的十进制 ASCII 值是 2,十六进制值是 0x02。

二者对应的ASCII码为:
在这里插入图片描述
然后第三个字符作为长度,之后就是根据解析到的长度来读取数据了,并且最后验证读取数据后的下一个字符是03。最终将数据转换为人类可读的字符串,如下图就是一个可被该解码器解析的例子:
在这里插入图片描述
开始字符 数据长度 数据 结束字符

package com.dahuyou.netty.customercodec.codec;import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToByteEncoder;//public class MyEncoder extends MessageToByteEncoder<String> {
public class MyEncoder extends MessageToByteEncoder {@Overrideprotected void encode(ChannelHandlerContext ctx, Object in, ByteBuf out) throws Exception {String msg = in.toString();byte[] bytes = msg.getBytes();byte[] send = new byte[bytes.length + 2];System.arraycopy(bytes, 0, send, 1, bytes.length);send[0] = 0x02;send[send.length - 1] = 0x03;out.writeInt(send.length);out.writeBytes(send);}
}

这里解码器可以暂时不用太关注,只是在数据的开头和结尾增加了STX和ETX,如下:
在这里插入图片描述
最后MyServerHandler的代码就比较简单了,如下:

package com.dahuyou.netty.customercodec.server;import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;import java.text.SimpleDateFormat;
import java.util.Date;public class MyServerHandler extends ChannelInboundHandlerAdapter {/*** 通道激活* @param ctx* @throws Exception*/@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {SocketChannel channel = (SocketChannel) ctx.channel();System.out.println("远端连接初始化,IP:" + channel.remoteAddress().getHostString() + ", port:" + channel.remoteAddress().getPort());// 通知客户端链接建立成功String str = "notify channel build success: " + " " + new Date() + " " + channel.localAddress().getHostString() + "\r\n";ctx.writeAndFlush(str);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {// 因为在初始化是已经设置了字符串的解码器,所以就不需要上述的手动读取二进制字节码的操作了,这就是框架的好处咯!System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " 接收到消息:" + msg);// 通知客户端链消息发送成功String str = "server received your msg: " + new Date() + " " + msg + "\r\n";ctx.writeAndFlush(str);}@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();System.out.println("异常信息:\r\n" + cause.getMessage());}/*** 当客户端主动断开服务端的链接后,这个通道就是不活跃的。也就是说客户端与服务端的关闭了通信通道并且不可以传输数据*/@Overridepublic void channelInactive(ChannelHandlerContext ctx) throws Exception {System.out.println("客户端断开链接" + ctx.channel().localAddress().toString());}
}

启动server,简单起见我们直接使用netassit测试:
在这里插入图片描述
以上代码相当于发送了byte数组[stx,4,‘a’.‘1’,‘b’,‘2’,etx]。
当然除了使用工具测试外,我们也可以程序来测试,主要是如下代码(详细看源码):

package com.dahuyou.netty.customercodec.client;import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.SocketChannel;import java.text.SimpleDateFormat;
import java.util.Date;public class MyClientHandler extends ChannelInboundHandlerAdapter {@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {System.out.println("通道建立成功");// 通知客户端链接建立成功
/*String str = "hello server , i'm client very happy connect to you." + " " + new Date() + " " + ((SocketChannel) ctx.channel()).localAddress().getHostString() + "\r\n";
*/String xxx = "a1b2";System.out.println(xxx.getBytes());byte[] bytes = xxx.getBytes();// 增加stx length etxbyte[] send = new byte[bytes.length + 3];System.arraycopy(bytes, 0, send, 2, bytes.length);send[0] = 0x02; // stxsend[1] = 0X34; // length 4的ASCII码是52 十六进制就是34send[send.length - 1] = 0x03; // etxByteBuf buf = Unpooled.buffer(send.length/* + 3*/); // + 3 stx 长度 etxbuf.writeBytes(send);//       ctx.writeAndFlush(str);ctx.writeAndFlush(buf);}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {//接收msg消息{与上一章节相比,此处已经不需要自己进行解码}System.out.println(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()) + " receive msg: " + msg);//通知客户端链消息发送成功
//        String str = "hello server received your msg: " + new Date() + " " + msg + "\r\n";
//        ctx.writeAndFlush(str);}
}

即channelActive中的逻辑,注意这里写入的都是ASCII码值。

写在后面

参考文章列表

Ascii完整码表(256个) 。
工具 › 开发类 › 进制转换 。
win的netassist TCP测试工具和Linux的nc工具使用 。

这篇关于netty编程之自定义编解码器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1100872

相关文章

Java AOP面向切面编程的概念和实现方式

《JavaAOP面向切面编程的概念和实现方式》AOP是面向切面编程,通过动态代理将横切关注点(如日志、事务)与核心业务逻辑分离,提升代码复用性和可维护性,本文给大家介绍JavaAOP面向切面编程的概... 目录一、AOP 是什么?二、AOP 的核心概念与实现方式核心概念实现方式三、Spring AOP 的关

C#中通过Response.Headers设置自定义参数的代码示例

《C#中通过Response.Headers设置自定义参数的代码示例》:本文主要介绍C#中通过Response.Headers设置自定义响应头的方法,涵盖基础添加、安全校验、生产实践及调试技巧,强... 目录一、基础设置方法1. 直接添加自定义头2. 批量设置模式二、高级配置技巧1. 安全校验机制2. 类型

SpringBoot AspectJ切面配合自定义注解实现权限校验的示例详解

《SpringBootAspectJ切面配合自定义注解实现权限校验的示例详解》本文章介绍了如何通过创建自定义的权限校验注解,配合AspectJ切面拦截注解实现权限校验,本文结合实例代码给大家介绍的非... 目录1. 创建权限校验注解2. 创建ASPectJ切面拦截注解校验权限3. 用法示例A. 参考文章本文

MySQL的JDBC编程详解

《MySQL的JDBC编程详解》:本文主要介绍MySQL的JDBC编程,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言一、前置知识1. 引入依赖2. 认识 url二、JDBC 操作流程1. JDBC 的写操作2. JDBC 的读操作总结前言本文介绍了mysq

Vite 打包目录结构自定义配置小结

《Vite打包目录结构自定义配置小结》在Vite工程开发中,默认打包后的dist目录资源常集中在asset目录下,不利于资源管理,本文基于Rollup配置原理,本文就来介绍一下通过Vite配置自定义... 目录一、实现原理二、具体配置步骤1. 基础配置文件2. 配置说明(1)js 资源分离(2)非 JS 资

Python异步编程之await与asyncio基本用法详解

《Python异步编程之await与asyncio基本用法详解》在Python中,await和asyncio是异步编程的核心工具,用于高效处理I/O密集型任务(如网络请求、文件读写、数据库操作等),接... 目录一、核心概念二、使用场景三、基本用法1. 定义协程2. 运行协程3. 并发执行多个任务四、关键

AOP编程的基本概念与idea编辑器的配合体验过程

《AOP编程的基本概念与idea编辑器的配合体验过程》文章简要介绍了AOP基础概念,包括Before/Around通知、PointCut切入点、Advice通知体、JoinPoint连接点等,说明它们... 目录BeforeAroundAdvise — 通知PointCut — 切入点Acpect — 切面

聊聊springboot中如何自定义消息转换器

《聊聊springboot中如何自定义消息转换器》SpringBoot通过HttpMessageConverter处理HTTP数据转换,支持多种媒体类型,接下来通过本文给大家介绍springboot中... 目录核心接口springboot默认提供的转换器如何自定义消息转换器Spring Boot 中的消息

C#异步编程ConfigureAwait的使用小结

《C#异步编程ConfigureAwait的使用小结》本文介绍了异步编程在GUI和服务器端应用的优势,详细的介绍了async和await的关键作用,通过实例解析了在UI线程正确使用await.Conf... 异步编程是并发的一种形式,它有两大好处:对于面向终端用户的GUI程序,提高了响应能力对于服务器端应

Python自定义异常的全面指南(入门到实践)

《Python自定义异常的全面指南(入门到实践)》想象你正在开发一个银行系统,用户转账时余额不足,如果直接抛出ValueError,调用方很难区分是金额格式错误还是余额不足,这正是Python自定义异... 目录引言:为什么需要自定义异常一、异常基础:先搞懂python的异常体系1.1 异常是什么?1.2