Thursday, April 21, 2016

To reconnect the WebSocket when it's disconnected

To reconnect the WebSocket when it's disconnected

        <script type="text/javascript">
            (function() {
                var data = document.getElementById("fileData");

                //var conn = new WebSocket("ws://{{.Host}}/ws?lastMod={{.LastMod}}");
                var conn = new ReconnectingWebSocket("wss://{{.Host}}/ws?lastMod={{.LastMod}}");

                conn.onclose = function(evt) {
                    console.log('Connection closed');
                }

                conn.onmessage = function(evt) {
                    console.log('file updated');

                    var obj = JSON.parse(evt.data);
                    console.log(obj);

                    data.textContent = obj.msg;
                }
            })();
        </script>

Reference:

https://github.com/joewalnes/reconnecting-websocket

https://github.com/gorilla/websocket/blob/master/examples/filewatch/main.go

http://blog.johnryding.com/post/78544969349/how-to-reconnect-web-sockets-in-a-realtime-web-app

http://stackoverflow.com/questions/3780511/reconnection-of-client-when-server-reboots-in-websocket

No comments: