gpt4 book ai didi

客户端断开连接时,node.js websocket 崩溃

转载 作者:搜寻专家 更新时间:2023-10-31 22:57:44 24 4
gpt4 key购买 nike

我是 NodeJSWebsockets 的新手,但我正在尝试使用它。

我所做的是从串行端口读取传入数据,然后使用 websocket 将这些数据发送到网页。从这里一切正常。

  • 我使用 node-static为我的网页提供服务
  • 我使用 ws对于网络套接字

问题是当客户端关闭他的浏览器时,我的 NodeJS websocket 服务器崩溃并出现以下错误:

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)

这是我的 websocket/serialport 代码:

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

谁能帮我弄清楚这里出了什么问题?

最佳答案

我认为,您应该在 closeerror 事件中从 CLIENTS 数组中删除套接字。否则它会尝试向已关闭的套接字发送消息。

关于客户端断开连接时,node.js websocket 崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24326413/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com