Query regarding reconnecting to websocket

406 views
Skip to first unread message

Julian Knight

unread,
Mar 27, 2015, 4:55:47 PM3/27/15
to node...@googlegroups.com
Not sure if I'm missing something obvious. Normally I use socket.io for websockets and it seems to reconnect on its own. When using raw websockets, this is not the case.

Are there any best practices or better yet, example code, to ensure reconnection without having to manually reload the page?

The problem is that whenever you update NR by hitting "Deploy", the socket is closed and so no further updates are received.

Regards, Julian.

Nicholas O'Leary

unread,
Mar 27, 2015, 5:03:00 PM3/27/15
to Node-RED Mailing LIst
Hi Julian,


You need to set an event handler for the 'close' event, which gets called when the socket closes. Within that event handler, you can attempt to reconnect after a suitable delay.

Nick

--
http://nodered.org
---
You received this message because you are subscribed to the Google Groups "Node-RED" group.
To unsubscribe from this group and stop receiving emails from it, send an email to node-red+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Dave C-J

unread,
Mar 27, 2015, 5:08:10 PM3/27/15
to node...@googlegroups.com
Julian

I do something like this
var wsUri = "your websocket url";

function start(wsUri) {  // Create the websocket
    console.log("CONNECT TO",wsUri);
    ws = new WebSocket(wsUri);

    ws.onopen = function(evt) {
        console.log("CONNECTED");
    };

    ws.onclose = function(evt) {
        console.log("DISCONNECTED");
        setTimeout(function(){ start(wsUri) }, 3000); // try to reconnect every 3 secs... bit fast ?
    }

    ws.onmessage = function (evt) {
        console.log("MESSAGE",evt);
        // do your stuff here
    }

    ws.onerror = function(evt) {
        console.log("ERROR",evt);
    }
}

start(wsUri);  // Connect the Websocket - to the URL

Julian Knight

unread,
Mar 27, 2015, 5:17:20 PM3/27/15
to node...@googlegroups.com
Thanks both, I'd feared that was the case.

I note that the non-accepted answer in Nicks reference is the correct method since it prevents multiple event triggers but also does a clear timer as well.

On Friday, 27 March 2015 21:08:10 UTC, Dave C-J wrote:
Julian

...

Julian Knight

unread,
Mar 27, 2015, 5:39:32 PM3/27/15
to node...@googlegroups.com
In case anyone else needs the code, here is an entire script that works correctly. Note that the ws node is configured to send the whole msg not just the payload in this instance.

    <script>
        var timerID=0;
        var ws;
        // We need to work out if we are connected with a secure or non-secure connection
        var wsProto = location.protocol == 'http:' ? 'ws:' : 'wss:';
        // And where we are connected
        var wsUri = wsProto + '//' + location.host + '/ws/sensors';

        var wsStart = function() {
            console.log( wsUri );
            ws = new WebSocket( wsUri );
           
            ws.onopen = function(){
                console.log( 'Web Socket open!' );
                // Handle reconnection case
                if(window.timerID){ /* a setInterval has been fired */
                    window.clearInterval(window.timerID);
                    window.timerID=0;
                }
            };
           
            ws.onclose = function(){
                console.log( 'Web Socket closed!' );
                // Handle disconnections
                if(!window.timerID){ /* avoid firing a new setInterval, after one has been done */
                    // Setup a function to reconnect every x milliseconds
                    window.timerID=setInterval(function(){
                        console.log("Timer fired");
                        wsStart();
                    }, 5000);
                }
            };

            ws.onerror = function(err){
                /*Send a small message to the console once the connection is established */
                console.log( '--- Web socket error: ---' );
                console.log( err );
            };
           
            ws.onmessage = function( wsMsg ){
                /*Send a small message to the console once the connection is established */
                var data = JSON.parse(wsMsg.data);
                console.log( '--- Web socket message: ' + data.topic + '---' );
                console.dir( data.payload );
                var id = data.payload.deviceLocation + "/" + data.payload.deviceType + "/" + data.payload.deviceName;
                $("#LM" + data.payload.deviceName).text(data.payload.lastModified);
            };
           
            // ws.send(JSON.stringify(message));
        };
       
        $( document ).ready(function() {
            wsStart();
        });
    </script>
Reply all
Reply to author
Forward
0 new messages