当仅调用一次emit时,会多次触发自定义事件

时间:2016-06-02 11:00:57

标签: javascript node.js sockets events

我正在使用ws模块来实现网络套接字。

名为newmessage的事件被触发等于使用web-socket-server打开的套接字数。我无法理解原因。虽然在调试时我发现只触发了一次emit,但是事件函数被调用了两次。

var SocketServer = require("./lib/SocketServer");

// Creating the object starts the server on this.socketPort
var sserver = new SocketServer(webSocketPort);
// Calling activateListeners on SocketServer instance, activates 
// all the event listeners associated with SocketServer
sserver.activateListeners();
sserver.on("newsocket",function(socket,status) {
    infoLogger.setMessage(`New socket opened: ${socket}`).log();
    sserver.on("newmessage",function(message,status) {
        // BEING CALLED  = NUMBER OF SOCKETS OPENED
        infoLogger.setMessage(`New message received: ${message}`).log();
    });
});

以下是SocketServer功能:

'use strict';

var WebSocketServer = require("ws").Server
  , EventEmitter = require("events").EventEmitter
  , util = require("util")
  , Logger = require("./Logger");


function SocketServer(port) {
    this.socketPort = port;
    // Starts WebSocket Server
    this.socketServer = new WebSocketServer({port: this.socketPort});
    var logger = new Logger(`Socket server started on ${this.socketPort}`,0).log();
}

util.inherits(SocketServer,WebSocketServer);

SocketServer.prototype.activateListeners = function() {
    var that = this;
    this.socketServer.on("connection",function(socket) {
        that.emit("newsocket",socket,200);
        socket.on("message",function(message) {
           that.emit("newmessage",message,200); 
        });
    });
};

// Exports
module.exports = SocketServer;

这可能是什么原因? newsocket事件仅被触发一次,只有在newmessage触发SocketServer事件时才会出现此问题。

1 个答案:

答案 0 :(得分:2)

每次调用EventEmitter.on()时,它都会添加另一个侦听器。当您发出事件时,它们会立即发射。

您可以进行一些检查以查看事件监听器是否已经存在,并避免再次添加它。