view transports/websocket.js @ 109:cd1f57661439 default tip

Fix files permissions.
author Emmanuel Gil Peyrot <linkmauve@linkmauve.fr>
date Wed, 01 Aug 2012 23:18:03 +0200
parents 5cb4733c5189
children
line wrap: on
line source

'use strict';

(function() {
  var WebSocket = window.WebSocket || window.MozWebSocket || undefined;

  if (typeof define !== 'undefined') {
    define(function() {
      return WebSocketTransport;
    });
  }
  else {
    Lightstring.WebSocketTransport = WebSocketTransport;
  }

  var WebSocketTransport = function(aService, aJid) {
    this.service = aService;
    this.jid = aJid;
  };
  WebSocketTransport.prototype = new EventEmitter();
  WebSocketTransport.prototype.open = function() {
    if(!WebSocket)
      return; //TODO: error

    this.socket = new WebSocket(this.service, 'xmpp');

    var that = this;
    this.socket.addEventListener('open', function() {
      if (this.protocol !== 'xmpp')
        ; //TODO: warning (Opera and Safari doesn't support this property)

      that.emit('open');

      var stream = Lightstring.stanzas.stream.open(that.jid.domain);
      var stanza = new Lightstring.Stanza();
      stanza.toString = function() {
        return stream;
      }
      that.send(stanza);
    });
    this.socket.addEventListener('error', function(e) {
      that.emit('disconnecting', e.data);
      //TODO: error
    });
    this.socket.addEventListener('close', function(e) {
      that.emit('disconnected', e.data);
    });
    this.socket.addEventListener('message', function(e) {
      var stanza = new Lightstring.Stanza(e.data);
      that.emit('in', stanza);
    });
  };
  WebSocketTransport.prototype.send = function(aStanza) {
    this.emit('out', aStanza);
    this.socket.send(aStanza.toString());
  };

})();