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

相关文章

shell编程之函数与数组的使用详解

《shell编程之函数与数组的使用详解》:本文主要介绍shell编程之函数与数组的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录shell函数函数的用法俩个数求和系统资源监控并报警函数函数变量的作用范围函数的参数递归函数shell数组获取数组的长度读取某下的

揭秘Python Socket网络编程的7种硬核用法

《揭秘PythonSocket网络编程的7种硬核用法》Socket不仅能做聊天室,还能干一大堆硬核操作,这篇文章就带大家看看Python网络编程的7种超实用玩法,感兴趣的小伙伴可以跟随小编一起... 目录1.端口扫描器:探测开放端口2.简易 HTTP 服务器:10 秒搭个网页3.局域网游戏:多人联机对战4.

Java并发编程必备之Synchronized关键字深入解析

《Java并发编程必备之Synchronized关键字深入解析》本文我们深入探索了Java中的Synchronized关键字,包括其互斥性和可重入性的特性,文章详细介绍了Synchronized的三种... 目录一、前言二、Synchronized关键字2.1 Synchronized的特性1. 互斥2.

使用Sentinel自定义返回和实现区分来源方式

《使用Sentinel自定义返回和实现区分来源方式》:本文主要介绍使用Sentinel自定义返回和实现区分来源方式,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Sentinel自定义返回和实现区分来源1. 自定义错误返回2. 实现区分来源总结Sentinel自定

Java的IO模型、Netty原理解析

《Java的IO模型、Netty原理解析》Java的I/O是以流的方式进行数据输入输出的,Java的类库涉及很多领域的IO内容:标准的输入输出,文件的操作、网络上的数据传输流、字符串流、对象流等,这篇... 目录1.什么是IO2.同步与异步、阻塞与非阻塞3.三种IO模型BIO(blocking I/O)NI

如何自定义Nginx JSON日志格式配置

《如何自定义NginxJSON日志格式配置》Nginx作为最流行的Web服务器之一,其灵活的日志配置能力允许我们根据需求定制日志格式,本文将详细介绍如何配置Nginx以JSON格式记录访问日志,这种... 目录前言为什么选择jsON格式日志?配置步骤详解1. 安装Nginx服务2. 自定义JSON日志格式各

Android自定义Scrollbar的两种实现方式

《Android自定义Scrollbar的两种实现方式》本文介绍两种实现自定义滚动条的方法,分别通过ItemDecoration方案和独立View方案实现滚动条定制化,文章通过代码示例讲解的非常详细,... 目录方案一:ItemDecoration实现(推荐用于RecyclerView)实现原理完整代码实现

Python异步编程中asyncio.gather的并发控制详解

《Python异步编程中asyncio.gather的并发控制详解》在Python异步编程生态中,asyncio.gather是并发任务调度的核心工具,本文将通过实际场景和代码示例,展示如何结合信号量... 目录一、asyncio.gather的原始行为解析二、信号量控制法:给并发装上"节流阀"三、进阶控制

基于Spring实现自定义错误信息返回详解

《基于Spring实现自定义错误信息返回详解》这篇文章主要为大家详细介绍了如何基于Spring实现自定义错误信息返回效果,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录背景目标实现产出背景Spring 提供了 @RestConChina编程trollerAdvice 用来实现 HTT

SpringSecurity 认证、注销、权限控制功能(注销、记住密码、自定义登入页)

《SpringSecurity认证、注销、权限控制功能(注销、记住密码、自定义登入页)》SpringSecurity是一个强大的Java框架,用于保护应用程序的安全性,它提供了一套全面的安全解决方案... 目录简介认识Spring Security“认证”(Authentication)“授权” (Auth