2
非常简单的node.js问题。我想扩展流对象以重新组合来自远程连接的数据。我正在做多个telnet并将命令发送到其他服务器,并且他们发送回应。它看起来像这样。“重新分块”node.js中的流对象
> Hello, this is a command
This is the response to the command.
Sometimes it pauses here (which triggers the 'data' event prematurely).
But the message isn't over until you see the semicolon
;
我想要做的是不是在暂停时触发'data'事件,而是等待;并触发定制的“消息”事件。
我读过并重读了this question,但我还没有完全理解它(部分原因是因为它涉及可写入的流,部分原因是我还没有注意到CoffeeScript)。
编辑:我想我要问两两件事在这里:
- 如何扩展/继承net.CreateConnection使用流对象?
- 我可以只扩展prototype.write做'拆分'并重新'发送'每个部分?
下面是我在做什么,到目前为止,可谓物美价廉,但分块应该是流,而不是“数据”侦听器中的一部分:如果我使用的是原始
var net = require('net');
var nodes = [
//list of ip addresses
];
function connectToServer(ip) {
var conn = net.createConnection(3083, ip);
conn.on('connect', function() {
conn.write ("login command;");
});
conn.on('data', function(data) {
var read = data.toString();
var message_list = read.split(/^;/m);
message_list.forEach (function(message) {
console.log("Atonomous message from " + ip + ':' + message);
//I need to extend the stream object to emit these instead of handling it here
//Also, sometimes the data chunking breaks the messages in two,
//but it should really wait for a line beginning with a ; before it emits.
});
});
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) {
connectToServer(node);
});
流,我想这将是这样的事情(基于我在别处找到的代码)?
var messageChunk = function() {
this.readable = true;
this.writable = true;
};
require("util").inherits(messageChunk, require("stream"));
messageChunk.prototype._transform = function (data) {
var regex = /^;/m;
var cold_storage = '';
if (regex.test(data))
{
var message_list = read.split(/^;/m);
message_list.forEach (function(message) {
this.emit("data", message);
});
}
else
{
//somehow store the data until data with a /^;/ comes in.
}
}
messageChunk.prototype.write = function() {
this._transform.apply(this, arguments);
};
但我没有使用原始流,我在net.createConnection对象返回中使用流对象。
你可以在这里发布你的代码吗?这会帮助你更容易。 – mzedeler 2013-03-23 18:54:19
那是怎么回事?任何人?我可能会以这种错误的方式去做 – 2013-04-02 18:59:02