Nodejs事件多次触发

时间:2013-12-13 16:33:12

标签: javascript node.js events zeromq

如果server01收到消息,则会触发server01和server02的消息事件。我想这行

Socket.prototype = new events.EventEmitter;

将导致完全独立的事件实例

感谢您的帮助!

var events = require('events');
var uuid = require('uuid');

// Server class
function Socket (host) {
  var self = this;

  self.options = {
    "serverHost": host,
    "serverName": "server",
    "clientName": uuid.v4()
  };

  self.socket = new require('zmq').socket('router');
  self.socket.identity = self.options.clientName;
  self.socket.connect('tcp://' + self.options.serverHost);

  self.socket.on('message', function (sender, data) {
    console.log('Sender: %s', self.options.clientName);
    console.log('Data: %s', data.toString());
    self.emit('message', sender, data);
  });

  setInterval(function () {
    self.socket.send([self.options.serverName, uuid.v4()]);
  }, 5000);

  self.send = function (obj, callback) {
    var status = true;

    if(obj !== 'object') {
      status = false;
    } else {
      self.socket.send([self.options.serverName, obj]);
    }

    if(callback === 'function') {
  callback(status);
    } else {
      return status;
    };
  };
};

Socket.prototype = new events.EventEmitter;

// Userland

var server01 = new Socket('127.0.0.1:3000');

server01.on('message', function (sender, data) {
  console.log('Server01: %s', data.toString());
});

var server02 = new Socket('127.0.0.1:3000');

server02.on('message', function (sender, data) {
  console.log('Server02: %s', data.toString());
});

以下是此脚本输出的示例

Sender: 14d36a66-a4e7-484a-9ce0-3f0d368a6986
Data: 03e6bb47-6af0-4700-9b95-7bbc310477f6
Server01: 03e6bb47-6af0-4700-9b95-7bbc310477f6
Server02: 03e6bb47-6af0-4700-9b95-7bbc310477f6
Sender: 59ec292e-abd2-4c9f-ac3e-2bf92c656fde
Data: d66cd320-c3f2-4842-b66b-1d89f656d32f
Server01: d66cd320-c3f2-4842-b66b-1d89f656d32f
Server02: d66cd320-c3f2-4842-b66b-1d89f656d32f

1 个答案:

答案 0 :(得分:1)

问题在于您管理继承的方式。正确的继承JavaScript代码是:

Socket.prototype = Object.create(EventEmitter.prototype);