[英]Websocket is unable to reconnect after restarting the server in Javascript
I have a simple client-side script like this:我有一个像这样的简单客户端脚本:
function connect() {
const { contextBridge } = require('electron');
var ws = new WebSocket('ws://localhost:3000');
ws.onerror = (error) => {
console.error(`Lost connection to server. Reason: ${error.message}`);
console.error('Attempting to reconnect...');
ws.close();
}
ws.onclose = (e) => {
setTimeout({
connect();
}, 500);
}
ws.addEventListener('open', () => {
console.log('Connected to server!');
});
// Some other stuff to call functions via the browser console
const API = {
ws_isOpen: () => { return ws.readyState === ws.OPEN }
}
contextBridge.exposeInMainWorld('api', API);
function send_msg(msg) {
// Process some data...
ws.send(msg);
}
}
connect();
It works normally when the server is running and it's trying to connect, or when the server is rebooting and it's trying to connect for the first time, but not while it's connected .当服务器正在运行并尝试连接时,它可以正常工作,或者当服务器重新启动并且第一次尝试连接时,但在连接时不能正常工作。 What I mean is that, if I were to suddenly shut the server down while the client is being connected to it, it attempts to try to reconnect as usual and the success message does pop up.
我的意思是,如果我在客户端连接到服务器时突然关闭服务器,它会尝试像往常一样尝试重新连接,并且会弹出成功消息。 However, if I type in
window.api.ws_isOpen()
in the browser console, it returns false
.但是,如果我在浏览器控制台中输入
window.api.ws_isOpen()
,它会返回false
。 When I try to send a message, an error pops up saying something like Websocket is already in CLOSING or CLOSED stage
.当我尝试发送消息时,会弹出一条错误消息,提示
Websocket is already in CLOSING or CLOSED stage
类的内容。 I tried changing the ws
variable type to let
and const
but it doesn't work.我尝试将
ws
变量类型更改为let
和const
但它不起作用。
Turns out the answer is really simple.原来答案很简单。 For some reason, when I put the
ws
variable outside the connect()
function and modify it in the function, it works.出于某种原因,当我将
ws
变量放在connect()
function 之外并在 function 中对其进行修改时,它可以工作。 I'm guessing it kinda re-declares/re-new the ws
variable.我猜它有点重新声明/重新更新
ws
变量。 It looks something like this:它看起来像这样:
var ws = null;
function connect() {
ws = new WebSocket('ws://localhost:3000');
// the exact same as above here....
}
connect();
After rebooting the server and letting it reconnect:重新启动服务器并让它重新连接后:
>> window.api.ws_isOpen()
true
I feel like I'm supposed to know how this works...我觉得我应该知道这是怎么回事...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.