Iris: Reconnect WebSocket on disconnection

Created on 18 Aug 2018  ·  2Comments  ·  Source: kataras/iris

How to reconnect the iris websocket on disconnection, without refreshing the client page?

Most helpful comment

Hello @kickbox, I guess this is more of a javascript question, but anyway, here is a quick example of how I would do it (you need to have the iris-ws.js included inside your page):

function InitWebsocket() {
    let websocket = new Ws('wss:yourwebsocketurl');
    let wsTimeout;
    let reconnectInterval= 5000;

    websocket.OnConnect(function() {
        clearTimeout(wsTimeout);
    });

    websocket.OnDisconnect(function() {
        wsTimeout = setTimeout(function() {
            InitWebsocket();
        }, reconnectInterval);
    });
}
InitWebsocket();

Basically on disconnect you just try to reconnect again every 5 seconds, until it connects and it resets the timeout interval, this can be extended according to your needs.

All 2 comments

Hello @kickbox, I guess this is more of a javascript question, but anyway, here is a quick example of how I would do it (you need to have the iris-ws.js included inside your page):

function InitWebsocket() {
    let websocket = new Ws('wss:yourwebsocketurl');
    let wsTimeout;
    let reconnectInterval= 5000;

    websocket.OnConnect(function() {
        clearTimeout(wsTimeout);
    });

    websocket.OnDisconnect(function() {
        wsTimeout = setTimeout(function() {
            InitWebsocket();
        }, reconnectInterval);
    });
}
InitWebsocket();

Basically on disconnect you just try to reconnect again every 5 seconds, until it connects and it resets the timeout interval, this can be extended according to your needs.

Thank you!

Was this page helpful?
0 / 5 - 0 ratings