Node.js TCP客户端命令/响应

时间:2011-07-16 16:49:22

标签: asynchronous node.js tcp client

我有一个简单的服务器,你发送一个命令,它回复一个\ r \ n分隔响应。

所以我试着在我的客户端上获得一个命令(回调)方法。看看这个简化的代码片段:

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(function(){})然后是一个client.command_2(function(){}),但是在我的command_2的回调中,我收到了来自command_1的响应。

这是实施此类事情的正确方法吗?

1 个答案:

答案 0 :(得分: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"