Stick Node.js 中 TCP 粘包、分包解决方案 项目简介
StickPackage,NodeJs 中 TCP 粘包、分包解决方案!配置介绍 提供对TCP粘包处理的解决方案 默认缓冲512个字节,当接收数据超过512字节,自动以512倍数扩大缓冲空间 本默认采用包头两个字节表示包长度 默认采用大端接模式接收数据 可以配置大端小端读取 可以配置自定义包头长度Changes:设置大端,小端接收,添加setReadIntBE,添加setReadIntLE方法:setReadIntBE(type) ,setReadIntLE(type) type:16 包头长度为2,short类型
setReadIntBE(type) ,setReadIntLE(type) type:32 包头长度为4,int类型安装npm i stickpackage使用方法var Stick = require('stickpackage');
let stick = new Stick(1024).setReadIntBE('16')
/*
* 包含两个数据包,10个字节,包头为short,两个字节:[0x00, 0x02],[ 0x00, 0x04]
* 数据包1:[0x00, 0x02, 0x66, 0x66]
* 数据包2:[0x00, 0x04, 0x88, 0x02, 0x11, 0x11]
*/
let data = Buffer.from([0x00, 0x02, 0x66, 0x66, 0x00, 0x04, 0x88, 0x02, 0x11, 0x11]);
/* 构造两个buffer
* data2_1包含: 第一个数据包的全部数据,第二个数据包的部分数据
* data2_2包含: 第二个数据包的剩余数据
*/
let data2_1 = Buffer.from([0x00, 0x00, 0x00, 0x02, 0x66, 0x66, 0x00, 0x04, 0x88, 0x02, 0x11]);
let data2_2 = Buffer.from([0x11]);
// 设置收到完整数据触发器
stick.onData(function (data) {
console.log('receive data,length:' + data.length);
console.log(data)
});
stick.putData(data);
stick.putData(data2_1);
stick.putData(data2_2);
// 运行结果:
// receive data,length:4 <Buffer 00 02 66 66>
// receive data,length:6 <Buffer 00 04 88 02 11 11>
// receive data,length:2< Buffer 00 00> receive data, length:4 < Buffer 00 02 66 66> receive data, length:6< Buffer
setReadIntBE(type) ,setReadIntLE(type) type:32 包头长度为4,int类型安装npm i stickpackage使用方法var Stick = require('stickpackage');
let stick = new Stick(1024).setReadIntBE('16')
/*
* 包含两个数据包,10个字节,包头为short,两个字节:[0x00, 0x02],[ 0x00, 0x04]
* 数据包1:[0x00, 0x02, 0x66, 0x66]
* 数据包2:[0x00, 0x04, 0x88, 0x02, 0x11, 0x11]
*/
let data = Buffer.from([0x00, 0x02, 0x66, 0x66, 0x00, 0x04, 0x88, 0x02, 0x11, 0x11]);
/* 构造两个buffer
* data2_1包含: 第一个数据包的全部数据,第二个数据包的部分数据
* data2_2包含: 第二个数据包的剩余数据
*/
let data2_1 = Buffer.from([0x00, 0x00, 0x00, 0x02, 0x66, 0x66, 0x00, 0x04, 0x88, 0x02, 0x11]);
let data2_2 = Buffer.from([0x11]);
// 设置收到完整数据触发器
stick.onData(function (data) {
console.log('receive data,length:' + data.length);
console.log(data)
});
stick.putData(data);
stick.putData(data2_1);
stick.putData(data2_2);
// 运行结果:
// receive data,length:4 <Buffer 00 02 66 66>
// receive data,length:6 <Buffer 00 04 88 02 11 11>
// receive data,length:2< Buffer 00 00> receive data, length:4 < Buffer 00 02 66 66> receive data, length:6< Buffer