如何将协议解析字节流读取与解析逻辑分离改写为一个长尾词的?
- 内容介绍
- 文章标签
- 相关推荐
本文共计221个文字,预计阅读时间需要1分钟。
javascriptBufferReader 读取 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; } _read(size) { this.needBytes=size; this.gFun(this); }}
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()//停止协议解析 })
本文共计221个文字,预计阅读时间需要1分钟。
javascriptBufferReader 读取 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; } _read(size) { this.needBytes=size; this.gFun(this); }}
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()//停止协议解析 })

