Backend Discussion Featured Javascript NodeJS

How to check connection status of websocket?

In web application development, you’d face a moment that need to check websocket connection status.
For example, you’d have a situation that your web backend needs to check if users are active in the browser.

It’s as very simple as you just need to check websocket property WebSocket.readyState. 
It has 4 possible values; “CONNECTING”, “OPEN”, “CLOSING”, “CLOSE”.

So for the above example, we can implement like following in Node.js.

setInterval(async () => {
    let i = 0;
    while (i < sockets.length) {
        const account = await Accounts.findById(sockets[i].account._id).exec();
        if (!((sockets[i].ws.readyState === WebSocket.OPEN) && account.isActive)) {
            account.isActive = sockets[i].ws.readyState === WebSocket.OPEN;
            await account.save();
        }

        const currentTime = Math.round((new Date()).getTime() / 1000);
        if (currentTime - sockets[i].timestamp > SESSION_TIME * 60) {
            if (sockets[i].ws.readyState === WebSocket.OPEN) {
                sockets[i].ws.send('WebSocket session expired.');
            }

            account.isActive = false;
            await account.save();

            sockets.splice(i, 1);
        } else {
            i++;
        }
    }
}, 10000);

The above code checks readyState of each users’ socket and marks them as “Active” so that other micro services will filter out them from processing.

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *