WebSockets that Reconnect

Here is a JavaScript sample of a WebSocket that will try to reconnect every second if the connection is lost to the server. This is completely transparent to the end-user.

function WS() {
  var _self = this;
  this.start = function() {
    var ws;
    ws = new WebSocket("ws://example.com/");					
    ws.onmessage = function(e) {	
      // Do something
    };
    ws.onclose = function(e) {
      clearTimeout(_self.refresh);
      setTimeout(_self.start, 1000);
    }            
  }
  _self.start();
} 
new WS();
This entry was posted in Technology and tagged , . Bookmark the permalink.

Leave a Reply

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

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">