我四处搜寻,要么找不到我要回答的确切问题,要么我需要有人像我 5 岁那样向我解释。
基本上,我有一个使用 Net 库的 Node.js 脚本。我连接到多个主机,发送命令,监听返回数据。
var net = require('net');
var nodes = [
'HOST1,192.168.179.8',
'HOST2,192.168.179.9',
'HOST3,192.168.179.10',
'HOST4,192.168.179.11'
];
function connectToServer(tid, ip) {
var conn = net.createConnection(23, ip);
conn.on('connect', function() {
conn.write (login_string); // login string hidden in pretend variable
});
conn.on('data', function(data) {
var read = data.toString();
if (read.match(/Login Successful/)) {
console.log ("Connected to " + ip);
conn.write(command_string);
}
else if (read.match(/Command OK/)) { // command_string returned successful,
// read until /\r\nEND\r\n/
// First part of data comes in here
console.log("Got a response from " + ip + ':' + read);
}
else {
//rest of data comes in here
console.log("Atonomous message from " + ip + ':' + read);
}
});
conn.on('end', function() {
console.log("Lost conncection to " + ip + "!!");
});
conn.on('error', function(err) {
console.log("Connection error: " + err + " for ip " + ip);
});
}
nodes.forEach(function(node) {
var nodeinfo = node.split(",");
connectToServer(nodeinfo[0], nodeinfo[1]);
});
数据最终被分成两个块。即使我将数据存储在哈希中,并在读取 /\r\nEND\r\n/ 分隔符时将第一部分附加到其余部分,中间也会丢失一个块。如何正确缓冲数据以确保从流中获得完整的消息?
编辑:好的,这似乎效果更好:
function connectToServer(tid, ip) {
var conn = net.createConnection(23, ip);
var completeData = '';
conn.on('connect', function() {
conn.write (login_string);
});
conn.on('data', function(data) {
var read = data.toString();
if (read.match(/Login Successful/)) {
console.log ("Connected to " + ip);
conn.write(command_string);
}
else {
completeData += read;
}
if (completeData.match(/Command OK/)) {
if (completeData.match(/\r\nEND\r\n/)) {
console.log("Response: " + completeData);
}
}
});
conn.on('end', function() {
console.log("Connection closed to " + ip );
});
conn.on('error', function(err) {
console.log("Connection error: " + err + " for ip " + ip);
});
}
我最大的问题显然是逻辑错误。我要么在等待开始回复的块,要么在等待结束它的块。我没有保存中间的所有东西。
我想如果我想了解所有关于它的 Node-ish,我应该在收到完整消息时触发一个事件(以空行开头,单独一行以 'END' 结尾),并在那里进行处理。