2011-07-16 67 views
1

我有一個簡單的服務器,您發送一個命令,它回覆一個\ r \ n分隔的響應。Node.js TCP客戶端命令/響應

所以我試圖在我的客戶端上得到一個命令(回調)方法。看看這個簡單的代碼片段:

var net = require('net'); 

var Client = function() { 
    this.data = ""; 
    this.stream = net.createConnection(port, host); 

    this.stream.on('data', function(data) { 
     var self = this; 

     this.data += data; 
     self.process()    
    }; 

    this.process = function() { 
     var _terminator = /^([^\r\n]*\r\n)/; 

     while(results = _terminator.exec(this.data)) { 
      var line = results[1]; 
      this.data = this.data.slice(line.length); 

      this.emit('response', data); 
     }; 
    }; 

    this.sendCommand = function(command, callback) { 
     var self = this; 

     var handler = function(data) { 
      self.removeListener('response', handler); 

      callback && callback(data); 
     } 

     this.addListener('response', handler); 

     this.stream.write(command); 
    }; 

    this.command_1 = function(callback) { 
     this.sendCommand('test', callback); 
    }; 

    this.command_2 = function(callback) { 
     this.sendCommand('test2', callback); 
    }; 
} 

所以我做了client.command_1(函數(){}),然後client.command_2(函數(){})但在我command_2我的回調我正在從command_1獲得響應。

這是實施這種事情的正確方法嗎?

+1

究竟是你想建立?有很多漂亮的節點模塊可以使用...你是否看過像socket.io這樣的東西?這是一個偉大的模塊來做實時的事情,如聊天等...... – pkyeck

+0

我知道,但我正在嘗試熟悉這樣的東西。 Socket.io是我首先想到的:) – mobius

+0

socket.io的全部是關於在* browser *和服務器之間進行雙向通信的api。它是隱藏瀏覽器差異和不同瀏覽器可以使用的不同傳輸。如果你想要服務器到服務器的通信,你有更多的選擇(WebSockets,http,rpc,xmlrpc,你自己的協議,消息隊列 - 你的名字) –

回答

0

當你執行

client.command_1(function() { 1; }); 
client.command_2(function() { 2; }); 

添加回調爲「結果」的聽衆,當emit('result')發生的第一次,這兩個回調被稱爲(當時第一個回調從列表中移除)。您需要在某種請求對象上設置回調,而不是在客戶端上。

在您的客戶端會發生什麼簡單的代碼:

var e = new EventEmitter(); 
e.on('result', function() { console.log(1); }); 
e.on('result', function() { console.log(2); }); 
// ... 
e.emit('result'); // here we trigger both callbacks which result in printing "1\n2\n" 
+0

我很確定是這樣,我需要一些幫助讓我走出我的循環。謝謝 :) – mobius