Home > database >  Websocket is unable to reconnect after restarting the server in Javascript
Websocket is unable to reconnect after restarting the server in Javascript

Time:08-27

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. When I try to send a message, an error pops up saying something like Websocket is already in CLOSING or CLOSED stage. I tried changing the ws variable type to let and const but it doesn't work.

CodePudding user response:

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. I'm guessing it kinda re-declares/re-new the ws variable. 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...

  • Related