FixedLengthFrameDecoder是固定长度解码器,它根据指定的长度自动对消息进行解码,开发者不需要考虑TCP拆包/粘包问题。
下面通过一个例子进行说明。

服务端:
在服务端的ChannelPipleline中增加FixedLengthFrameDecoder,长度设置为20,然后依次增加字符串解码器和自定义的EchoServerHandler。

/*** 使用FixedLengthFrameDecoder解码器解决TCP粘包/拆包问题。** @author j.tommy* @version 1.0* @date 2017/11/18*/
public class EchoServer {public static void main(String[] args) {EventLoopGroup bossGroup = new NioEventLoopGroup();EventLoopGroup workerGroup = new NioEventLoopGroup();ServerBootstrap b = new ServerBootstrap();b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, 1024).handler(new LoggingHandler(LogLevel.INFO)).childHandler(new ChannelInitializer<SocketChannel>() {protected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(20)); // 固定长度解码器,长度设置为20socketChannel.pipeline().addLast(new StringDecoder());socketChannel.pipeline().addLast(new EchoServerHandler());}});try {ChannelFuture f = b.bind(8899).sync();f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();} finally {bossGroup.shutdownGracefully();workerGroup.shutdownGracefully();}}
}
class EchoServerHandler extends ChannelHandlerAdapter {private int counter;@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {String body = (String) msg;System.out.println("接收到客户端请求:" + body + ",counter=" + ++counter);// 响应客户端ByteBuf resp = Unpooled.copiedBuffer(body.getBytes());ctx.write(resp);}@Overridepublic void channelReadComplete(ChannelHandlerContext ctx) throws Exception {ctx.flush();}
}

客户端:
在客户端的ChannelPipleline中增加FixedLengthFrameDecoder,长度设置为20,然后依次增加字符串解码器和自定义的EchoClientHandler。

/*** @author j.tommy* @version 1.0* @date 2017/11/18*/
public class EchoClient {public static void main(String[] args) {EventLoopGroup group = new NioEventLoopGroup();Bootstrap b = new Bootstrap();b.group(group).channel(NioSocketChannel.class).option(ChannelOption.TCP_NODELAY,true).handler(new ChannelInitializer<SocketChannel>() {protected void initChannel(SocketChannel socketChannel) throws Exception {socketChannel.pipeline().addLast(new FixedLengthFrameDecoder(20));socketChannel.pipeline().addLast(new StringDecoder());socketChannel.pipeline().addLast(new EchoClientHandler());}});try {ChannelFuture f = b.connect("127.0.0.1",8899).sync();f.channel().closeFuture().sync();} catch (InterruptedException e) {e.printStackTrace();}finally {group.shutdownGracefully();}}
}
class EchoClientHandler extends ChannelHandlerAdapter {private int counter = 0;@Overridepublic void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {ctx.close();}@Overridepublic void channelActive(ChannelHandlerContext ctx) throws Exception {String req = "hello,this message is from client.";ByteBuf sendBuf = null;for (int i=0;i<100;i++) {sendBuf = Unpooled.copiedBuffer(req.getBytes());ctx.writeAndFlush(sendBuf);}}@Overridepublic void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {String resp = (String) msg;System.out.println("接收到服务端响应:"  + resp + ",counter=" + ++counter);}
}

示例中,客户端发送的消息是hello,this message is from client.
因为按照固定长度截取,所以服务端接收到的是这样的:

参考《Netty权威指南》

Netty固定长度解码器相关推荐

  1. Netty教程(九)——解码器

    https://juejin.cn/post/6889632659979862029 ByteToMessageDecoder 看看ByteToMessageDecoder这个解码器的channelR ...

  2. python字符串按长度分割_python 按照固定长度分割字符串的方法小结

    有如下的一堆mac地址,需要更改成一定格式,如mac='902B345FB021'改为mac='90-2B-34-5F-B0-21'. 借助python脚本,可以轻松实现,原理就是:字符串的按照固定长 ...

  3. java随机产生100个大小写字母_Java生成固定长度的随机字符串(以大小写字母和数字)...

    packageorg.jimmy.autosearch2019.test;importjava.util.ArrayList;importjava.util.Random;/***@authorラピス ...

  4. Java编程笔试时输入问题:如何输入固定长度、不定长度的一维数组?如何输入固定长度、不定长度的二维数组?

    Java编程笔试时输入问题: 如何输入固定长度.不定长度的一维数组? 如何输入固定长度.不定长度的二维数组? 如何将数组中的内容直接输出,不要中括号和逗号? 文章目录 ==Java编程笔试时输入问题= ...

  5. python长度分割文本_python 按照固定长度分割字符串的方法小结

    有如下的一堆mac地址,需要更改成一定格式,如mac='902B345FB021'改为mac='90-2B-34-5F-B0-21'. 借助python脚本,可以轻松实现,原理就是:字符串的按照固定长 ...

  6. Java生成固定长度的随机字符串(以大小写字母和数字)

    package org.jimmy.autosearch2019.test;import java.util.ArrayList; import java.util.Random;/*** @auth ...

  7. ASP.NET - 截取固定长度字符串显示在页面,多余部分显示为省略号

    ASP.NET - 截取固定长度字符串显示在页面,多余部分显示为省略号 方法一: publicstaticstring GetString(string str, int length){int i ...

  8. struct 模块 把一个类型,如数字,转成固定长度的bytes

    该模块可以把一个类型,如数字,转成固定长度的bytes import structheaders=struct.pack('i',132333) print(headers,len(headers)) ...

  9. 栈(Stack) 任何程序执行前,预先分配一固定长度的内存空间

    内存是什么及其用处,但内存是不能随便使用的,因为操作系统自己也要使用内存,而且现在的操作系统正常情况下都是多任务操作系统,即可同时执行多个程序,即使只有一个CPU.因此如果不对内存访问加以节制,可能会 ...

最新文章

  1. R语言names函数获取或者设置数据对象名称实战
  2. 汇编(8086cpu): ip寄存器与指令的关系
  3. Python如何实现24个微信大群(共万人)同步转发直播?
  4. linux 文件夹的颜色代表什么意思
  5. python 匹配字符串map lambda函数_Python map amp; reduce 以及lambda匿名函数 - jvisualvm - ITeye博客...
  6. 信息学奥赛一本通(1063:最大跨度值)
  7. 在Ubuntu中下载github上的文件
  8. 手机压缩照片怎么压缩?分享一个轻松压缩的方法
  9. IB选课指南及热门专业选课建议
  10. 使用Depix进行马赛克的消除测试
  11. python实现MACD策略背离点的判断
  12. C++虚函数、多继承和虚基类学习心得 内存布局
  13. 用计算机怎么打出箭头,怎么打出箭头
  14. 买电脑常识——电脑性能
  15. 京东代挂获取不到ck怎么解决
  16. Unity --- 触摸方法,以及灯光与烘培的使用
  17. KunlunBase集群管理接口
  18. window 10 禁用笔记本触摸板
  19. rpm提示:XXX conflicts with file form package XXX
  20. 源代码转换:Tangible Software Solutions v22.10.20

热门文章

  1. Windows 环境JDK环境配置
  2. 《A fast and elitist multiobjective genetic algorithm: NSGA-II》阅读笔记
  3. 2022-2028全球皮肤科冷冻外科装置市场现状及未来发展趋势
  4. el-color-picker-sheldon使用说明(一款基于Vue和ElementUI的取色器)
  5. Centos 6安装Maven
  6. 【动手学深度学习】06-ResNet解析
  7. 不同分布所表示的物理含义
  8. 如何快速搭建线上电商商城网站?
  9. IAP Cannot connect to iTunes Store
  10. 02 锁版本--通用模块--knife4j--profiles