node.js websocket crashes when client disconnect -
node.js websocket crashes when client disconnect -
i new nodejs
, websockets
, trying play it.
what read incoming datas serial port, send these datas web page using websocket. here works fine.
i utilize node-static serve web page i utilize ws websocketthe problem when client close browser, nodejs websocket server crashes next 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 @ websocket.send (/root/node-v0.10.29/lib/node_modules/ws/lib/websocket.js:187:16) @ sendall (/root/app/socketserver.js:30:16) @ serialport.<anonymous> (/root/app/socketserver.js:58:8) @ serialport.emit (events.js:95:17) @ object.module.exports.raw [as parser] (/root/node-v0.10.29/bin/node_modules/serialport/parsers.js:8:13) @ object.serialport.options.datacallback (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:143:15) @ serialportfactory.serialport._emitdata (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:312:20) @ afterread (/root/node-v0.10.29/bin/node_modules/serialport/serialport.js:290:18) @ /root/node-v0.10.29/bin/node_modules/serialport/serialport.js:304:9 @ object.wrapper [as oncomplete] (fs.js:459:17)
here 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 incoming info 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 incoming info browser websockets. sendall(senddata); }); }); }
can help me figure out what's wrong here ?
i think, should remove socket clients
array on both close
, error
event. otherwise tries send message socket closed.
node.js websocket
Comments
Post a Comment