jcordingley
jcordingley

Reputation: 31

nodejs Websocket Server - possible EventEmitter memory leak detected

I'm relatively new to node and im struggling to find the answers!

I've created a very basic node script that is used to connect to a rs232 serial device, at the same time it serves as a websocket server so that clients can connect to it to get live output from the rs232 device but i keep getting event emitter max listeners errors after 11 clients have connected.

If any one can help me here or if i've gone about the code the wrong way give some advice it would be appreciated.

Thanks Jamie

heres the code

var serialport = require("serialport");
var SerialPort = serialport.SerialPort;
var WebSocketServer = require("ws").Server;

var serialPort = new SerialPort("COM5", {
  baudrate: 9600,
  parser: serialport.parsers.readline("\n")
});

var wss = new WebSocketServer({ port: 3000 });

serialPort.on("open", function () {

  console.log('open');

    var weight = 0;

    wss.on("connection", function(ws) {

        serialPort.on('data', function(data) {

            weight = data.toString();

            wss.clients.forEach(function(wssclient) {
                wssclient.send(weight);
            });

        });

    });

});

Upvotes: 0

Views: 917

Answers (1)

jfriend00
jfriend00

Reputation: 707258

If your connection handler, you add a new event handler serialPort.on('data', ...). So, for every new incoming websocket connection, you add a new event handler for the serialPort. And, you never remove those either. So, they just accumulate forever and they all do the same thing too.

The warning you see is because the eventEmitter object sees an accumulation of event handlers all for the same message and suspects something might be wrong.

Instead, you can move that out of the connection handler and do all your processing in just one event handler:

serialPort.on('data', function(data) {
    var weight = data.toString();
    wss.clients.forEach(function(wssclient) {
        wssclient.send(weight);
    });
});

serialPort.on("open", function () {
    console.log('open');
    wss.on("connection", function(ws) {
        // code here that needs to happen upon connection
    });
});

Upvotes: 3

Related Questions