Sha256: 70330eaca0515bc753a506d23f1c5c3b62cdac5614a2f518fe15a2033588a2ca

Contents?: true

Size: 1.45 KB

Versions: 13

Compression:

Stored size: 1.45 KB

Contents

var WebSocketIO = function(){
  new EventEmitter().apply(this);
  this.url = "<%= websocketio_url %>";
  this.session = null;
  this.websocket = null;
  this.connecting = false;
  var reconnect_timer_id = null;
  var running = false;
  var self = this;

  self.on("__session_id", function(session_id){
    self.session = session_id;
    self.emit("connect", self.session);
  });

  this.connect = function(){
    if(typeof WebSocket === 'undefined'){
      self.emit("error", "websocket not exists");
      return null;
    }
    self.running = true;
    var url = self.session ? self.url+'/session='+self.session : self.url;
    self.websocket = new WebSocket(url);
    self.websocket.onmessage = function(e){
      try{
        var data_ = JSON.parse(e.data);
        self.emit(data_.type, data_.data);
      }
      catch(e){
        self.emit("error", "WebSocketIO get error");
      }
    };
    self.websocket.onclose = function(){
      if(self.connecting) self.emit("disconnect");
      self.connecting = false;
      if(self.running){
        reconnect_timer_id = setTimeout(self.connect, 10000);
      }
    };
    self.websocket.onopen = function(){
      self.connecting = true;
    };
    return self;
  };

  this.close = function(){
    clearTimeout(reconnect_timer_id);
    self.running = false;
    self.websocket.close();
  };

  this.push = function(type, data){
    self.websocket.send(JSON.stringify({type: type, data: data, session: self.session}));
  };
};

Version data entries

13 entries across 13 versions & 1 rubygems

Version Path
sinatra-websocketio-0.1.6 lib/js/websocketio.js
sinatra-websocketio-0.1.5 lib/js/websocketio.js
sinatra-websocketio-0.1.4 lib/js/websocketio.js
sinatra-websocketio-0.1.3 lib/js/websocketio.js
sinatra-websocketio-0.1.2 lib/js/websocketio.js
sinatra-websocketio-0.1.1 lib/js/websocketio.js
sinatra-websocketio-0.1.0 lib/js/websocketio.js
sinatra-websocketio-0.0.6 lib/js/websocketio.js
sinatra-websocketio-0.0.5 lib/js/websocketio.js
sinatra-websocketio-0.0.4 lib/js/websocketio.js
sinatra-websocketio-0.0.3 lib/js/websocketio.js
sinatra-websocketio-0.0.2 lib/js/websocketio.js
sinatra-websocketio-0.0.1 lib/js/websocketio.js