Reconnect Websocket after connection loss

Asked

Viewed 590 times

1

I use this code to connect to my server with Websockets:

(function(nameSpace) {
  function createMethod(method, options, stateCallback) {
    var that = this;
    this[method] = function() {
      if (stateCallback && stateCallback.apply) {
        stateCallback(method);
      }
      console.info(method);
      if (options[method] && options[method].apply) {
        options[method].apply(that, arguments);
      }
    };
  }

  function SocketWrapper(options) {
    var ws,
      events = ['onopen', 'onmessage', 'onclose', 'onerror'],
      i, len, prop = {
        opened: false,
        closed: false,
        error: false
      },
      method;

    if (typeof options === 'undefined' || !options) {
      throw 'ArgumentException: please add default constructor options';
    }

    this.queue = [];

    this.onEventTrigger = function(eventName) {
      var i, len;
      if (eventName === 'onopen') {
        prop.opened = true;
        prop.closed = false;
        // openend send queue
        if (this.queue.length > 0) {
          for (i = this.queue.length; --i >= 0;) {
            this.send.apply(this, this.queue[0]);
            this.queue.splice(0, 1);
          }
        }
      }
      if (eventName === 'onerror') {
        prop.error = true;
      }
      if (eventName === 'onclosed') {
        prop.opened = false;
        prop.closed = true;
      }
    };

    this.init = function() {
      var cb = this.onEventTrigger.bind(this);
      ws = new WebSocket(options.url);

      for (i = 0; i < events.length; i++) {
        method = events[i];
        createMethod.apply(ws, [method, options, cb]);
      }
    };

    this.send = function() {
      if (prop.closed) {
        throw 'InvalidOperation: Cannot send messages to a closed Websocket!';
      }
      if (!prop.opened) {
        this.queue.push(arguments);
      } else {
        ws.send.apply(ws, arguments);
      }
    };

    this.init();
    return this;
  }

  window.SocketWrapper = SocketWrapper;
}(window));

var socket = new window.SocketWrapper({
  url: 'ws://127.0.0.1:1805',
  onopen: function() {
    this.send('message', 'hi');
  },
  onmessage: function() {
    console.log(arguments);
  },
  onclose: function() {
    socket = null;
  },
  onerror: function() {
    console.log('error occured, oh no!');
    console.error(arguments);
  }
});
socket.send('i am message send to soon, but since i check the state of the ws object, i will be queued and send when appropriate');

This code suits me, was the solution I found for my case, but I wanted him to reconnect as soon as the connection was lost, he kept trying to reconnect until he did.. don’t know much how to adapt because it’s not mine, how to proceed?

  • Different from your other question, here you should check it in the event Onclose.

  • @Qmechanic73 yes I know, but how to force him to re-connect from there?

  • I have an idea, but I have a way to test, I don’t know if it’s viable either, I can risk an answer. =/

  • @Qmechanic73 any idea is worth a haha answer

  • Of that line(var socket = new window.SocketWrapper({) down delete and try to implement this code, I did not test, see if something occurs. =)

  • @Qmechanic73 worked, great idea! I’ll stay testing, thank you!!

  • @Qmechanic73 tested and works correctly, thank you dnv =)

  • I posted the answer. I accidentally used return socket = new window.SocketWrapper.. at the beginning of the function, remove the socket = .

Show 3 more comments

1 answer

3


When the connection is lost the event onclose is triggered, to make the reconnection you must work on that event.

One mode you can use to connect again is through the function setTimeout, she will perform an action each n seconds.

Instead declare the variable socket with all that code, do it in a function:

function CreateSocketWrapper(){
    return new window.SocketWrapper({
      url: 'ws://127.0.0.1:1805',
      onopen: function() {
        this.send('message', 'hi');
      },
      onmessage: function() {
        console.log(arguments);
      },
      onclose: function() {
        setTimeout(function(){CreateSocketWrapper()}, 5000); // 5 segundos
      },
      onerror: function() {
        console.log('error occured, oh no!');
        console.error(arguments);
      }
    });
}

And to use it:

var socket = CreateSocketWrapper();
socket.send('i am message send to soon, but since i check the state of...');

Browser other questions tagged

You are not signed in. Login or sign up in order to post.