NodeJS:什么是处理TCP套接字stream的正确方法? 我应该使用哪个分隔符?

根据我在这里所理解的,“V8有一个世代垃圾收集器,随机移动对象,节点不能得到一个指向原始string数据的指针来写入套接字。 所以我不应该将来自TCPstream的数据存储在string中,特别是如果该string变得比Math.pow(2,16)字节更大。 (希望我到现在为止..)

那么什么是处理来自TCP套接字的所有数据的最佳方式? 到目前为止,我一直试图使用_:_:_作为分隔符,因为我认为它是某种独特的,不会混淆其他的东西。

数据的一个样本将会是something_:_:_maybe a large text_:_:_ maybe tons of lines_:_:_more and more data

这是我试图做的:

 net = require('net'); var server = net.createServer(function (socket) { socket.on('connect',function() { console.log('someone connected'); buf = new Buffer(Math.pow(2,16)); //new buffer with size 2^16 socket.on('data',function(data) { if (data.toString().search('_:_:_') === -1) { // If there's no separator in the data that just arrived... buf.write(data.toString()); // ... write it on the buffer. it's part of another message that will come. } else { // if there is a separator in the data that arrived parts = data.toString().split('_:_:_'); // the first part is the end of a previous message, the last part is the start of a message to be completed in the future. Parts between separators are independent messages if (parts.length == 2) { msg = buf.toString('utf-8',0,4) + parts[0]; console.log('MSG: '+ msg); buf = (new Buffer(Math.pow(2,16))).write(parts[1]); } else { msg = buf.toString() + parts[0]; for (var i = 1; i <= parts.length -1; i++) { if (i !== parts.length-1) { msg = parts[i]; console.log('MSG: '+msg); } else { buf.write(parts[i]); } } } } }); }); }); server.listen(9999); 

每当我尝试console.log('MSG' + msg) ,它会打印出整个缓冲区,所以没有用,看看是否有用。

我怎样才能正确处理这些数据? 懒惰的模块工作,即使这个数据不是面向行的? 有没有其他模块来处理不是面向行的stream?

确实已经有人说,有额外的工作正在进行,因为Node必须采取缓冲区,然后将其推入到V8 /将其转换为string。 但是,在缓冲区上执行toString()并不会更好。 目前没有很好的解决scheme,据我所知,特别是如果你的最终目标是弄个string,然后玩弄它。 其中一件事Ryan提到@ nodeconf是一个需要完成工作的领域。

至于分隔符,你可以select任何你想要的。 许多二进制协议select包含一个固定的头文件,这样你就可以把东西放在一个正常的结构中,这个结构很多次都包含了一个长度。 通过这种方式,可以分割已知的头文件,并获取有关其余数据的信息,而不必遍历整个缓冲区。 用这样的scheme,可以使用如下工具:

另外,可以通过数组语法来访问缓冲区,也可以使用.slice()来分割缓冲区。

最后,在这里检查: https : //github.com/joyent/node/wiki/modules – find一个模块,parsing一个简单的TCP协议,似乎做得很好,并阅读一些代码。

你应该使用新的stream2 api。 http://nodejs.org/api/stream.html

这里有一些非常有用的例子: https : //github.com/substack/stream-handbook