netty之LengthFieldBasedFrameDecoder解码器
官方api:http://netty.io/4.1/api/io/netty/handler/codec/LengthFieldBasedFrameDecoder.html
package com.eshore.ismp.hbinterface.sps; import java.nio.charset.Charset; import org.apache.log4j.Logger;
import org.springframework.context.support.ClassPathXmlApplicationContext; import com.eshore.ismp.hbinterface.service.BizCommonService; import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder; public class SpsServer4 {
private static final Logger logger = Logger.getLogger(SpsServer4.class);
private static int PORT = 10002;
/**用于分配处理业务线程的线程组个数 */
protected static final int BIZGROUPSIZE = Runtime.getRuntime().availableProcessors()*2; //默认
/** 业务出现线程大小*/
protected static final int BIZTHREADSIZE = 4;
/*
* NioEventLoopGroup实际上就是个线程池,
* NioEventLoopGroup在后台启动了n个NioEventLoop来处理Channel事件,
* 每一个NioEventLoop负责处理m个Channel,
* NioEventLoopGroup从NioEventLoop数组里挨个取出NioEventLoop来处理Channel
*/
private static final EventLoopGroup bossGroup = new NioEventLoopGroup(BIZGROUPSIZE);
private static final EventLoopGroup workerGroup = new NioEventLoopGroup(BIZTHREADSIZE); protected static void run(final BizCommonService bizCommonService) throws Exception {
//String PORTs=ConfigLoadUtil.getValue("toSpsServerPort");
//PORT=Integer.parseInt(PORTs);
//logger.info("PORT IS:"+PORT);
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup);
b.channel(NioServerSocketChannel.class);
b.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
/* pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));
pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8)); */
pipeline.addLast(new MessageDecoder(Integer.MAX_VALUE,18,4,-22,0));
pipeline.addLast("decoder", new StringDecoder(Charset.forName("GBK")));
pipeline.addLast("encoder", new StringEncoder(Charset.forName("GBK")));
pipeline.addLast(new SpsServerHandler(bizCommonService));
}
}); b.bind(PORT).sync();
logger.info("TCP服务器已启动");
} protected static void shutdown() {
workerGroup.shutdownGracefully();
bossGroup.shutdownGracefully();
} public static void main(String[] args) throws Exception {
try{
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "applicationContext.xml" });
context.start();
BizCommonService bizCommonService = (BizCommonService) context.getBean("bizCommonService");
SpsServer4.run(bizCommonService);
}catch(Exception e){
logger.error("start sps interface server error:",e);
System.exit(-1);
}
}
}
MessageDecoder:
package com.eshore.ismp.hbinterface.sps; import java.io.UnsupportedEncodingException;
import java.nio.ByteOrder; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.DecoderException;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder; public class MessageDecoder extends LengthFieldBasedFrameDecoder{
private final Logger logger = LoggerFactory.getLogger(this.getClass());
public MessageDecoder(int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment,
int initialBytesToStrip) {
super(maxFrameLength, lengthFieldOffset, lengthFieldLength, lengthAdjustment, initialBytesToStrip);
} @Override
protected Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception{
return super.decode(ctx, in);
}
@Override
protected long getUnadjustedFrameLength(ByteBuf buf, int offset, int length, ByteOrder order){
long frameLength;
switch (length) {
case 1:
frameLength = buf.getUnsignedByte(offset);
break;
case 2:
frameLength = buf.getUnsignedShort(offset);
break;
case 3:
frameLength = buf.getUnsignedMedium(offset);
break;
case 4:
//frameLength = buf.getUnsignedInt(offset);
frameLength=buf.readableBytes();
logger.info("==="+frameLength);
byte[] cc=new byte[buf.readableBytes()];
ByteBuf tmp=buf.copy();
tmp.readBytes(cc);
try {
String ss=new String(cc,"GBK");
frameLength=Integer.parseInt(ss.substring(offset,offset+length));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
break;
case 8:
frameLength = buf.getLong(offset);
break;
default:
throw new DecoderException(
"unsupported lengthFieldLength: "
+ length + " (expected: 1, 2, 3, 4, or 8)");
}
return frameLength;
} }
其中,报文长度为6位:17-22
参考 https://blog.csdn.net/bestone0213/article/details/47108419
参考:https://www.jianshu.com/p/a0a51fd79f62
参考:https://blog.csdn.net/zougen/article/details/79037675
netty之LengthFieldBasedFrameDecoder解码器的更多相关文章
- Netty 中 LengthFieldBasedFrameDecoder 构造函数取值备忘
public LengthFieldBasedFrameDecoder(ByteOrder byteOrder, int maxFrameLength, int lengthFieldOffset, ...
- Netty学习(六)-LengthFieldBasedFrameDecoder解码器
在TCP协议中我们知道当我们在接收消息时候,我们如何判断我们一次读取到的包就是整包消息呢,特别是对于使用了长连接和使用了非阻塞I/O的程序.上节我们也说了上层应用协议为了对消息进行区分一般采用4种方式 ...
- netty中LengthFieldBasedFrameDecoder的使用
在org.jboss.netty.handler.codec.frame包中,有LengthFieldBasedFrameDecoder类用来解析带有长度属性的包,只要我们在传输协议中加入包的总长度就 ...
- 【Netty】使用解码器Decoder解决TCP粘包和拆包问题
解码器Decoder和ChannelHandler的关系 netty的解码器通常是继承自ByteToMessageDecoder,而它又是继承自ChannelInboundHandlerAdapter ...
- 基于Netty的私有协议栈的开发
基于Netty的私有协议栈的开发 书是人类进步的阶梯,每读一本书都使自己得以提升,以前看书都是看了就看了,当时感觉受益匪浅,时间一长就又还回到书本了!所以说,好记性不如烂笔头,以后每次看完一本书都写一 ...
- netty通用解码器LengthFieldBasedFrameDecoder
2.2.4. LengthFieldBasedFrameDecoder解码器 了解TCP通信机制的读者应该都知道TCP底层的粘包和拆包,当我们在接收消息的时候,显示不能认为读取到的报文就是个整包消息, ...
- Netty源码分析 (十一)----- 拆包器之LengthFieldBasedFrameDecoder
本篇文章主要是介绍使用LengthFieldBasedFrameDecoder解码器自定义协议.通常,协议的格式如下: LengthFieldBasedFrameDecoder是netty解决拆包粘包 ...
- Netty 解码器抽象父类 ByteToMessageDecoder 源码解析
前言 Netty 的解码器有很多种,比如基于长度的,基于分割符的,私有协议的.但是,总体的思路都是一致的. 拆包思路:当数据满足了 解码条件时,将其拆开.放到数组.然后发送到业务 handler 处理 ...
- Netty源码分析第6章(解码器)---->第1节: ByteToMessageDecoder
Netty源码分析第六章: 解码器 概述: 在我们上一个章节遗留过一个问题, 就是如果Server在读取客户端的数据的时候, 如果一次读取不完整, 就触发channelRead事件, 那么Netty是 ...
随机推荐
- Framework 7 日历插件改成Picker 模式
Framework 7 里面的日历插件默认的2种模式: 1.文本框 2.直接展示 如下图: 更多例子点这里 而我的需求如下图: 点击小图标再弹出日历,选择某个日期,隐藏日历弹层. 实现步骤: 1.写小 ...
- CMM已经落伍了,敏捷才是王道
首先强调一下,敏捷和有没有文档一点关系都没有.我只是对于CMM的那些文档感觉有些浪费. 看看那些文档,看看那些流程.想想那些伟大的软件作品,哪个是用CMM开发出来的? 作为测试工程师,程序员的你在CM ...
- imx6 gpio分析
本文主要介绍如何配置IOMUX寄存器,设置IO复用寄存器,配置为GPIO功能.参考: http://www.jianshu.com/p/3c2053508342 http://www.embest-t ...
- R语言hist绘图函数
hist 用于绘制直方图,下面介绍每个参数的作用: 1)x: 用于绘制直方图的数据,该参数的值为一个向量 代码示例: data <- c(rep(1, 10), rep(2, 5), rep(3 ...
- MySQL(二)之服务管理与配置文件修改和连接MySQL
上一篇给大家介绍了怎么在linux和windows中安装mysql,本来是可以放在首页的,但是博客园说“安装配置类文件”不让放在首页.接下来给大家介绍一下在linux和windows下MySQL的一下 ...
- CentOS7忘记root密码的解决方法
开机启动centos 7.0,看到如下画面,选择下图选单,按"e"键 在下图linux16行中,将ro这两个字母修改为rw init=/sysroot/bin/sh 修改结果如下图 ...
- Case用法
SELECT <myColumnSpec> = CASE WHEN <A> THEN <somethingA> WHEN <B> THEN <so ...
- BootStrap中按钮点击后被禁用按钮的最佳实现方法
//禁用button $('button').addClass('disabled'); // Disables visually $('button').prop('disabled', true) ...
- SQL 2005 如何只安装客户端?
在“注册信息”输入合适的用户名和公司后,点击[下一步],在“要安装的组件”界面中选择要安装的组件:根据我们的需要来选择要安装的组件(各组件的说明如下表),这里我勾选所有的组件:我们可以点击 [高级 ...
- [转]wcout输出中文却不显示出来
准备使用UNICODE来写个控制台测试程序发现,cout无法输出UNICODE的中文字符.查找C++标准看到,其提供了wcin.wcout.wcerr.wclog用于处理wchar_t字符的输入输出. ...