简体   繁体   中英

Custom event being fired multiple times when emit is called only once

I am using ws module to implement web sockets.

The event named newmessage is being fired equal to the number of sockets open with the web-socket-server. I could not understand the reason. Although on debugging I found that the emit is fired only once, but the event function is called twice.

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();
    });
});

Here is the SocketServer function:

'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;

What could be the reason for this? newsocket event gets fired only once and the problem occurs only with newmessage event fired by SocketServer .

Every time you call EventEmitter.on( ) it adds another listener. When you emit your event, they all fire at once.

You can put some checks to see if the event listener already exists and avoid adding it again if it does.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM