У меня есть простой сервер, вы отправляете ему команду, он отвечает обратно ответом с разделителем \ 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.
Это правильный способ реализовать такую вещь?