0. 链接
1. 公共模块
- 封装公共方法的父类
- constructor: 初始化编码/解码的protobufSchema
- encode:编码成二进制数据
- decode:二进制数据解码
- isCompleteRequest:判断buffer,并返回下一条完整数据的长度
- onDataEventFn:socket接收数据事件封装,分割处理流数据,处理每条数据后调用回调函数
module.exports = class {
constructor(protobufEncodeSchema, protobufDecodeSchema){
this.protobufEncodeSchema = protobufEncodeSchema
this.protobufDecodeSchema = protobufDecodeSchema
}
decode(buffer) {
const seq = buffer.readUInt32BE();
return {
seq: seq,
result: this.protobufDecodeSchema.decode(buffer.slice(8))
}
}
isCompleteRequest(buffer) {
if (buffer.length < 8) {
return 0
}
const bodyLength = buffer.readInt32BE(4);
if (buffer.length >= bodyLength + 8) {
return bodyLength + 8
} else {
return 0
}
}
encode(data, seq) {
const body = this.protobufEncodeSchema.encode(data);
const head = Buffer.alloc(8);
head.writeUInt32BE(seq);
head.writeUInt32BE