如何捕获和处理“WebSocket已处于CLOSING或CLOSED状态”在节点中 [英] How to catch and deal with "WebSocket is already in CLOSING or CLOSED state" in Node
问题描述
我一直在寻找解决问题的方法WebSocket已经处于CLOSING或CLOSED状态并发现:
I've been searching for a solution to the issue "WebSocket is already in CLOSING or CLOSED state" and found this:
- Meteor WebSocket is already in CLOSING or CLOSED state error
- WebSocket is already in CLOSING or CLOSED state.
答案#1与Meteor严格相关,而#2没有答案。我有一个带有套接字的节点服务器应用程序:
Answer #1 is for strictly related to Meteor and #2 has no answers... I have a Node server app with a socket:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ server });
wss.on('connection', function connection(socket) {
socket.on('message', function incoming(data) {
console.log('Incoming data ', data);
});
});
客户连接如下:
const socket = new WebSocket('ws://localhost:3090'); //Create WebSocket connection
//Connection opened
socket.addEventListener('open', function(event) {
console.log("Connected to server");
});
//Listen to messages
socket.addEventListener('message', function(event) {
console.log('Message from server ', event);
});
然而,几分钟后,客户端随机断开连接并且函数
However after a few minutes, clients randomly disconnect and the function
socket.send(JSON.stringify(data));
然后抛出WebSocket已处于CLOSING或CLOSED状态。。
Will then throw a "WebSocket is already in CLOSING or CLOSED state.".
我正在寻找一种方法来检测和处理这些断开连接并立即再次尝试连接。
I am looking for a way to detect and deal these disconnections and immediately attempt to connect again.
什么是最正确有效的方法吗?
推荐答案
最简单的方法是检查套接字是否打开或不是在发送之前。
The easiest way is to check if the socket is open or not before sending.
例如 - 写一个简单的函数:
For example - write a simple function:
function isOpen(ws) { return ws.readyState === ws.OPEN }
然后 - 之前任何 socket.send
确保它已打开:
Then - before any socket.send
make sure it is open:
if (!isOpen(socket)) return;
socket.send(JSON.stringify(data));
您还可以重写发送
函数此答案但以我的方式您可以记录这种情况。
You can also rewrite the send
function like this answer but in my way you can log this situations.
并且,对于您的第二个请求
And, for your second request
立即尝试再次连接
immediately attempt to connect again
您无法从服务器执行此操作。
There is no way you can do it from the server.
客户端代码应监控WebSocket状态并根据您的需要应用重新连接方法。
The client code should monitor the WebSocket state and apply reconnect method based on your needs.
例如 - 查看这个 VueJS库可以很好地完成它。查看启用ws自动重新连接部分
For example - check this VueJS library that do it nicely. Look at Enable ws reconnect automatically section
这篇关于如何捕获和处理“WebSocket已处于CLOSING或CLOSED状态”在节点中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!