I have a simple server, you send it a command, it replies back with an \r\n delimited response.
So I tried to get a command( callback ) method on my client. Check out this simplified code snippet:
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 );
};
}
So I am doing a client.command_1( function() {} ) and then a client.command_2( function() {}) but in the callback of my command_2 I am getting the response from command_1.
Is this the right way to implement such a thing?
When you execute
you add both callbacks as ‘result’ listeners, and when
emit('result')happens for the first time, both callback are called (then first callback removes itself from a list). You need to set callbacks on some kind of request object, not on a client.simple code on what happens in your client: