2013-03-22 39 views
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)。

編輯:我想我要問兩兩件事在這裏:

  1. 如何擴展/繼承net.CreateConnection使用流對象?
  2. 我可以只擴展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對象返回中使用流對象。

+0

你可以在這裏發佈你的代碼嗎?這會幫助你更容易。 – mzedeler 2013-03-23 18:54:19

+0

那是怎麼回事?任何人?我可能會以這種錯誤的方式去做 – 2013-04-02 18:59:02

回答

0

不要使用直接實現的_transform,_read,_write或_flush函數,這些函數用於節點的內部使用。

當您看到字符「;」時發出自定義事件在你的流中:

var msg = ""; 
conn.on("data",function(data) { 
    var chunk = data.toString(); 
    msg += chunk; 
    if(chunk.search(";") != -1) { 
    conn.emit("customEvent",msg); 
    msg = ""; 
    } 
}); 
conn.on("customEvent",function(msg) { 
    //do something with your message 
});