当前位置 : 主页 > 网络编程 > JavaScript >

协议解析字节流读取与解析逻辑分离

来源:互联网 收集:自由互联 发布时间:2021-06-28
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
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(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()//停止协议解析
})
上一篇:uadirect
下一篇:自增Id生成器
网友评论