Buffer读取 const Readable = require('stream').Readable;class BufferReader extends Readable { constructor(options) { super(options); } init(gFun) { this.readBytes = 0; this.poolBytes = 0; this.needBytes = 0; this.gFun = gFun; this.need(thi
const Readable = require('stream').Readable;
class BufferReader extends Readable {
constructor(options) {
super(options);
}
init(gFun) {
this.readBytes = 0;
this.poolBytes = 0;
this.needBytes = 0;
this.gFun = gFun;
this.need(this.gFun.next(false).value);
}
stop() {
this.gFun.return(true);
}
push(buf) {
super.push(buf);
this.poolBytes += buf.length;
this.readBytes += buf.length;
let enough = this.needBytes > 0 && this.needBytes <= this.poolBytes
while (enough) {
enough = this.need(this.gFun.next(this.read(this.needBytes)).value);
}
}
read(size) {
this.poolBytes -= size;
return super.read(size);
}
need(size) {
this.needBytes = size;
return this.poolBytes >= size;
}
}
module.exports = BufferReader
解析字节流
let br = new BufferReader()
br.init(decode())
function * decode(){
let buf = yield 4;//读取4个字节(缓存里如果不够4个字节,则等待直到有4个字节就会继续执行)
buf = yield 8;//读取8个字节
……
}
收到字节数据添加到Buffer
socket.on('data',data=>{
br.push(data)
}).on('close',()=>{
br.stop()//停止协议解析
})
