Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js websocket crashes when client disconnect

I am very new to NodeJS and Websockets, but i am trying to play with it.

What i do is read incoming datas from Serial port, then send these datas to a web page using websocket. From here everything works fine.

  • I use node-static to serve my web page
  • I use ws for websocket

The problem is when a client close his browser, then my NodeJS websocket server crashes with the following error :

root@WS-SERVER-2:~/app# node socketserver.js
open serial communication
Client disconnected.

/root/node-v0.10.29/lib/node_modules/ws/lib/WebSocket.js:187
    else throw new Error('not opened');
               ^
Error: not opened
    at WebSocket.send (/root/node-v0.10.29/lib/node_modules/ws/lib/WebSocket.js:187:16)
    at sendAll (/root/app/socketserver.js:30:16)
    at SerialPort.<anonymous> (/root/app/socketserver.js:58:8)
    at SerialPort.emit (events.js:95:17)
    at Object.module.exports.raw [as parser] (/root/node-v0.10.29/bin/node_modules/serialport/parsers.js:8:13)
    at Object.SerialPort.options.dataCallback (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:143:15)
    at SerialPortFactory.SerialPort._emitData (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:312:20)
    at afterRead (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:290:18)
    at /root/node-v0.10.29/bin/node_modules/serialport/serialport.js:304:9
    at Object.wrapper [as oncomplete] (fs.js:459:17)

Here is my websocket/serialport code :

var WebSocketServer = require('../node-v0.10.29/lib/node_modules/ws').Server;
var SerialPort = require('../node-v0.10.29/bin/node_modules/serialport').SerialPort;

var serialPort;
var portName = '/dev/ttyACM0';
var sendData = "";
var wss = new WebSocketServer({port: 8080});

var CLIENTS=[];

wss.on('connection', function(ws) {
       CLIENTS.push(ws);
    ws.on('message', function(message) {
        console.log('received: %s', message);
        sendAll(message);
    });
    ws.on('close', function() {
        console.log('Client disconnected.');
    });
    ws.on('error', function() {
        console.log('ERROR');
    });
    ws.send("");
});

function sendAll(message)
{
for(var i=0;i<CLIENTS.length;i++)
    {
    CLIENTS[i].send(message);
    }
}

serialListener();

function serialListener(debug)
{
    var receivedData = "";
    serialPort = new SerialPort(portName, {
        baudrate: 9600,
         dataBits: 8,
         parity: 'none',
         stopBits: 1,
         flowControl: false
    });

    serialPort.on("open", function () {
      console.log('open serial communication');
            // Listens to incoming data
        serialPort.on('data', function(data) {
             receivedData += data.toString();
          if (receivedData .indexOf('E') >= 0 && receivedData .indexOf('B') >= 0) {
           sendData = receivedData .substring(receivedData .indexOf('B') + 1, receivedData .indexOf('E'));
           receivedData = '';
         }
         // send the incoming data to browser with websockets.
       sendAll(sendData);
      });
    });
}

Can someone help me to figure out what's wrong here ?

like image 572
user2196728 Avatar asked Dec 08 '22 07:12

user2196728


2 Answers

I think, you should remove the socket from your CLIENTS array on both close and error event. Otherwise it tries to send a message to a socket that is closed.

like image 52
rkusa Avatar answered Dec 11 '22 09:12

rkusa


I was having this same issue. Turned out I was attempting to send events to sockets that were in the "closing" state. Checking that each socket was specifically open before broadcasting a message fixed it for me:

    function sendAll(data){
        for(var i = 0; i < clients.length; i++){
            if(this.clients[i].readyState != this.clients[0].OPEN){
                console.error('Client state is ' + this.clients[i].readyState);
            }
            else{
                this.clients[i].send(data);
            }
        }
    }
like image 33
jbll Avatar answered Dec 11 '22 08:12

jbll