我试图使用Node.js的ReadLine与套接字,如下所示:
var net = require('net');
var rl = require('readline');
this.streamServer = net.createServer(function (socket) {
var i = rl.createInterface(socket, socket);
i.on('line', function (line) {
socket.write(line);
});
});
this.streamServer.maxConnections = 1;
this.streamServer.listen(7001);
Run Code Online (Sandbox Code Playgroud)
当我远程登录到端口7001并开始输入文本时,它会在我按下回车之前立即回复给我.
为什么ReadLine不等待全线?
我也尝试了.question(),我得到了相同的结果......在收到任何数据时触发回调,而不等待行尾字符.
编辑:这甚至更奇怪.当我使用Windows telnet客户端进行测试时,我得到了上面提到的行为.但是,如果我使用PuTTY作为客户端进行测试,ReadLine即使在Windows上也能正常工作.我做了一些数据包捕获.也许有人可以对此有所了解?未缩进的行是来自客户端的数据.缩进行是服务器回复.
使用Windows Telnet
00000000 61 a
00000000 61 a
00000001 62 b
00000001 62 b
00000002 63 c
00000002 63 c
00000003 64 d
00000003 64 d
00000004 65 e
00000004 65 e
00000005 66 f
00000005 66 f …Run Code Online (Sandbox Code Playgroud) 从我的理解在这里,"V8拥有世代垃圾收集器.移动对象随机风靡,节点不能得到一个指向原始字符串数据写入到插座." 所以我不应该将来自TCP流的数据存储在字符串中,特别是如果该字符串变得大于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 …Run Code Online (Sandbox Code Playgroud)