Переглянути джерело

socket only streaming works, socket close handler

Michelle Bu 12 роки тому
батько
коміт
f1062f695f
4 змінених файлів з 108 додано та 147 видалено
  1. 36 49
      demo/static/peer.js
  2. 36 49
      dist/peer.js
  3. 0 0
      dist/peer.min.js
  4. 36 49
      lib/peer.js

+ 36 - 49
demo/static/peer.js

@@ -871,9 +871,6 @@ function Peer(options) {
 
   // Queued connections to make.
   this._queued = [];
-
-  // Make sure connections are cleaned up.
-  window.onbeforeunload = this._cleanup;
 };
 
 util.inherits(Peer, EventEmitter);
@@ -893,12 +890,12 @@ Peer.prototype._checkIn = function() {
             var response = JSON.parse(http.responseText.split('\n').shift());
             if (!!response.id) {
               self._id = response.id;
-              //self._socketInit();
+              self._socketInit();
               self.emit('ready', self._id);
               self._processQueue();
             }
           } catch (e) {
-            //self._socketInit();
+            self._socketInit();
           }
         }
         self._handleStream(http, true);
@@ -906,11 +903,11 @@ Peer.prototype._checkIn = function() {
       http.send(null);
     } catch(e) {
       util.log('XMLHttpRequest not available; defaulting to WebSockets');
-      //this._socketInit();
+      this._socketInit();
     }
   } else {
     this._startXhrStream();
-    //this._socketInit();
+    this._socketInit();
   }
   // TODO: may need to setInterval in case handleStream is not being called
   // enough.
@@ -962,7 +959,10 @@ Peer.prototype._socketInit = function() {
   if (!!this._socket)
     return;
 
-  this._socket = new WebSocket('ws://' + this._server + '/ws?id=' + this._id);
+  var wsurl = 'ws://' + this._server + '/ws';
+  if (!!this._id)
+    wsurl += '?id=' + this._id;
+  this._socket = new WebSocket(wsurl);
 
   var self = this;
   this._socket.onmessage = function(event) {
@@ -985,75 +985,67 @@ Peer.prototype._socketInit = function() {
 
 
 Peer.prototype._handleServerMessage = function(message) {
-  var msg;
-  try {
-    msg = JSON.parse(message);
-  } catch(e) {
-    switch (message) {
-      case 'end':
-        util.log('XHR stream timed out.');
-        if (!this._socketOpen)
-          this._startXhrStream();
-        break;
-      case 'socket':
+  message = JSON.parse(message);
+  var peer = message.src;
+  var connection = this.connections[peer];
+  switch (message.type) {
+    // XHR stream closed by timeout.
+    case 'HTTP-END':
+      util.log('XHR stream timed out.');
+      if (!this._socketOpen)
+        this._startXhrStream();
+      break;
+    // XHR stream closed by socket connect.
+    case 'HTTP-SOCKET':
         util.log('XHR stream closed, WebSocket connected.');
         break;
-      case 'error':
+    case 'HTTP-ERROR':
         util.log('Something went wrong.');
         break;
-      default:
-        util.log('Message unrecognized:', message);
-        break;
-    }
-    return;
-  }
-  var peer = msg.src;
-  var connection = this.connections[peer];
-  switch (msg.type) {
     case 'ID':
       if (!this._id) {
         // If we're just now getting an ID then we may have a queue.
-        this._id = msg.id;
+        this._id = message.id;
         this.emit('ready', this._id);
         this._processQueue();
       }
       break;
     case 'ERROR':
-      this.emit('error', msg.msg);
-      util.log(msg.msg);
+      this.emit('error', message.msg);
+      util.log(message.msg);
       break;
     case 'OFFER':
       var options = {
-        metadata: msg.metadata,
-        sdp: msg.sdp,
+        metadata: message.metadata,
+        sdp: message.sdp,
         socketOpen: this._socketOpen,
         config: this._config
       };
       var self = this;
       var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, function(err, connection) {
         if (!err) {
-          self.emit('connection', connection, msg.metadata);
+          self.emit('connection', connection, message.metadata);
         }
       }, options);
       this._attachConnectionListeners(connection);
       this.connections[peer] = connection;
       break;
     case 'ANSWER':
-      if (connection) connection.handleSDP(msg);
+      if (connection) connection.handleSDP(message);
       break;
     case 'CANDIDATE':
-      if (connection) connection.handleCandidate(msg);
+      if (connection) connection.handleCandidate(message);
       break;
     case 'LEAVE':
       if (connection) connection.handleLeave();
       break;
     case 'PORT':
       if (util.browserisms === 'Firefox') {
-        connection.handlePort(msg);
+        connection.handlePort(message);
         break;
       }
     case 'DEFAULT':
-      util.log('Unrecognized message type:', msg.type);
+      util.log('Unrecognized message type:', message.type);
       break;
   }
 };
@@ -1068,20 +1060,14 @@ Peer.prototype._processQueue = function() {
 
 
 Peer.prototype._cleanup = function() {
-  if (this._socketOpen) {
-    this._socket.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
-  } else {
-    var http = new XMLHttpRequest();
-    http.open('post', this._httpUrl + '/leave', true);
-    http.setRequestHeader('Content-Type', 'application/json');
-    http.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
-  }
-
   for (var peer in this.connections) {
     if (this.connections.hasOwnProperty(peer)) {
       this.connections[peer].close();
     }
   }
+
+  if (this._socketOpen)
+    this._socket.close();
 };
 
 /** Listeners for DataConnection events. */
@@ -1096,6 +1082,8 @@ Peer.prototype._attachConnectionListeners = function(connection) {
 
 /** Exposed connect function for users. Will try to connect later if user
  * is waiting for an ID. */
+// TODO: pause XHR streaming when not in use and start again when this is
+// called.
 Peer.prototype.connect = function(peer, metadata, cb) {
   if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
 
@@ -1121,7 +1109,6 @@ Peer.prototype.destroy = function() {
 
 
 exports.Peer = Peer;
-
 function DataConnection(id, peer, socket, httpUrl, cb, options) {
   if (!(this instanceof DataConnection)) return new DataConnection(options);
   EventEmitter.call(this);

+ 36 - 49
dist/peer.js

@@ -871,9 +871,6 @@ function Peer(options) {
 
   // Queued connections to make.
   this._queued = [];
-
-  // Make sure connections are cleaned up.
-  window.onbeforeunload = this._cleanup;
 };
 
 util.inherits(Peer, EventEmitter);
@@ -893,12 +890,12 @@ Peer.prototype._checkIn = function() {
             var response = JSON.parse(http.responseText.split('\n').shift());
             if (!!response.id) {
               self._id = response.id;
-              //self._socketInit();
+              self._socketInit();
               self.emit('ready', self._id);
               self._processQueue();
             }
           } catch (e) {
-            //self._socketInit();
+            self._socketInit();
           }
         }
         self._handleStream(http, true);
@@ -906,11 +903,11 @@ Peer.prototype._checkIn = function() {
       http.send(null);
     } catch(e) {
       util.log('XMLHttpRequest not available; defaulting to WebSockets');
-      //this._socketInit();
+      this._socketInit();
     }
   } else {
     this._startXhrStream();
-    //this._socketInit();
+    this._socketInit();
   }
   // TODO: may need to setInterval in case handleStream is not being called
   // enough.
@@ -962,7 +959,10 @@ Peer.prototype._socketInit = function() {
   if (!!this._socket)
     return;
 
-  this._socket = new WebSocket('ws://' + this._server + '/ws?id=' + this._id);
+  var wsurl = 'ws://' + this._server + '/ws';
+  if (!!this._id)
+    wsurl += '?id=' + this._id;
+  this._socket = new WebSocket(wsurl);
 
   var self = this;
   this._socket.onmessage = function(event) {
@@ -985,75 +985,67 @@ Peer.prototype._socketInit = function() {
 
 
 Peer.prototype._handleServerMessage = function(message) {
-  var msg;
-  try {
-    msg = JSON.parse(message);
-  } catch(e) {
-    switch (message) {
-      case 'end':
-        util.log('XHR stream timed out.');
-        if (!this._socketOpen)
-          this._startXhrStream();
-        break;
-      case 'socket':
+  message = JSON.parse(message);
+  var peer = message.src;
+  var connection = this.connections[peer];
+  switch (message.type) {
+    // XHR stream closed by timeout.
+    case 'HTTP-END':
+      util.log('XHR stream timed out.');
+      if (!this._socketOpen)
+        this._startXhrStream();
+      break;
+    // XHR stream closed by socket connect.
+    case 'HTTP-SOCKET':
         util.log('XHR stream closed, WebSocket connected.');
         break;
-      case 'error':
+    case 'HTTP-ERROR':
         util.log('Something went wrong.');
         break;
-      default:
-        util.log('Message unrecognized:', message);
-        break;
-    }
-    return;
-  }
-  var peer = msg.src;
-  var connection = this.connections[peer];
-  switch (msg.type) {
     case 'ID':
       if (!this._id) {
         // If we're just now getting an ID then we may have a queue.
-        this._id = msg.id;
+        this._id = message.id;
         this.emit('ready', this._id);
         this._processQueue();
       }
       break;
     case 'ERROR':
-      this.emit('error', msg.msg);
-      util.log(msg.msg);
+      this.emit('error', message.msg);
+      util.log(message.msg);
       break;
     case 'OFFER':
       var options = {
-        metadata: msg.metadata,
-        sdp: msg.sdp,
+        metadata: message.metadata,
+        sdp: message.sdp,
         socketOpen: this._socketOpen,
         config: this._config
       };
       var self = this;
       var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, function(err, connection) {
         if (!err) {
-          self.emit('connection', connection, msg.metadata);
+          self.emit('connection', connection, message.metadata);
         }
       }, options);
       this._attachConnectionListeners(connection);
       this.connections[peer] = connection;
       break;
     case 'ANSWER':
-      if (connection) connection.handleSDP(msg);
+      if (connection) connection.handleSDP(message);
       break;
     case 'CANDIDATE':
-      if (connection) connection.handleCandidate(msg);
+      if (connection) connection.handleCandidate(message);
       break;
     case 'LEAVE':
       if (connection) connection.handleLeave();
       break;
     case 'PORT':
       if (util.browserisms === 'Firefox') {
-        connection.handlePort(msg);
+        connection.handlePort(message);
         break;
       }
     case 'DEFAULT':
-      util.log('Unrecognized message type:', msg.type);
+      util.log('Unrecognized message type:', message.type);
       break;
   }
 };
@@ -1068,20 +1060,14 @@ Peer.prototype._processQueue = function() {
 
 
 Peer.prototype._cleanup = function() {
-  if (this._socketOpen) {
-    this._socket.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
-  } else {
-    var http = new XMLHttpRequest();
-    http.open('post', this._httpUrl + '/leave', true);
-    http.setRequestHeader('Content-Type', 'application/json');
-    http.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
-  }
-
   for (var peer in this.connections) {
     if (this.connections.hasOwnProperty(peer)) {
       this.connections[peer].close();
     }
   }
+
+  if (this._socketOpen)
+    this._socket.close();
 };
 
 /** Listeners for DataConnection events. */
@@ -1096,6 +1082,8 @@ Peer.prototype._attachConnectionListeners = function(connection) {
 
 /** Exposed connect function for users. Will try to connect later if user
  * is waiting for an ID. */
+// TODO: pause XHR streaming when not in use and start again when this is
+// called.
 Peer.prototype.connect = function(peer, metadata, cb) {
   if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
 
@@ -1121,7 +1109,6 @@ Peer.prototype.destroy = function() {
 
 
 exports.Peer = Peer;
-
 function DataConnection(id, peer, socket, httpUrl, cb, options) {
   if (!(this instanceof DataConnection)) return new DataConnection(options);
   EventEmitter.call(this);

Різницю між файлами не показано, бо вона завелика
+ 0 - 0
dist/peer.min.js


+ 36 - 49
lib/peer.js

@@ -32,9 +32,6 @@ function Peer(options) {
 
   // Queued connections to make.
   this._queued = [];
-
-  // Make sure connections are cleaned up.
-  window.onbeforeunload = this._cleanup;
 };
 
 util.inherits(Peer, EventEmitter);
@@ -54,12 +51,12 @@ Peer.prototype._checkIn = function() {
             var response = JSON.parse(http.responseText.split('\n').shift());
             if (!!response.id) {
               self._id = response.id;
-              //self._socketInit();
+              self._socketInit();
               self.emit('ready', self._id);
               self._processQueue();
             }
           } catch (e) {
-            //self._socketInit();
+            self._socketInit();
           }
         }
         self._handleStream(http, true);
@@ -67,11 +64,11 @@ Peer.prototype._checkIn = function() {
       http.send(null);
     } catch(e) {
       util.log('XMLHttpRequest not available; defaulting to WebSockets');
-      //this._socketInit();
+      this._socketInit();
     }
   } else {
     this._startXhrStream();
-    //this._socketInit();
+    this._socketInit();
   }
   // TODO: may need to setInterval in case handleStream is not being called
   // enough.
@@ -123,7 +120,10 @@ Peer.prototype._socketInit = function() {
   if (!!this._socket)
     return;
 
-  this._socket = new WebSocket('ws://' + this._server + '/ws?id=' + this._id);
+  var wsurl = 'ws://' + this._server + '/ws';
+  if (!!this._id)
+    wsurl += '?id=' + this._id;
+  this._socket = new WebSocket(wsurl);
 
   var self = this;
   this._socket.onmessage = function(event) {
@@ -146,75 +146,67 @@ Peer.prototype._socketInit = function() {
 
 
 Peer.prototype._handleServerMessage = function(message) {
-  var msg;
-  try {
-    msg = JSON.parse(message);
-  } catch(e) {
-    switch (message) {
-      case 'end':
-        util.log('XHR stream timed out.');
-        if (!this._socketOpen)
-          this._startXhrStream();
-        break;
-      case 'socket':
+  message = JSON.parse(message);
+  var peer = message.src;
+  var connection = this.connections[peer];
+  switch (message.type) {
+    // XHR stream closed by timeout.
+    case 'HTTP-END':
+      util.log('XHR stream timed out.');
+      if (!this._socketOpen)
+        this._startXhrStream();
+      break;
+    // XHR stream closed by socket connect.
+    case 'HTTP-SOCKET':
         util.log('XHR stream closed, WebSocket connected.');
         break;
-      case 'error':
+    case 'HTTP-ERROR':
         util.log('Something went wrong.');
         break;
-      default:
-        util.log('Message unrecognized:', message);
-        break;
-    }
-    return;
-  }
-  var peer = msg.src;
-  var connection = this.connections[peer];
-  switch (msg.type) {
     case 'ID':
       if (!this._id) {
         // If we're just now getting an ID then we may have a queue.
-        this._id = msg.id;
+        this._id = message.id;
         this.emit('ready', this._id);
         this._processQueue();
       }
       break;
     case 'ERROR':
-      this.emit('error', msg.msg);
-      util.log(msg.msg);
+      this.emit('error', message.msg);
+      util.log(message.msg);
       break;
     case 'OFFER':
       var options = {
-        metadata: msg.metadata,
-        sdp: msg.sdp,
+        metadata: message.metadata,
+        sdp: message.sdp,
         socketOpen: this._socketOpen,
         config: this._config
       };
       var self = this;
       var connection = new DataConnection(this._id, peer, this._socket, this._httpUrl, function(err, connection) {
         if (!err) {
-          self.emit('connection', connection, msg.metadata);
+          self.emit('connection', connection, message.metadata);
         }
       }, options);
       this._attachConnectionListeners(connection);
       this.connections[peer] = connection;
       break;
     case 'ANSWER':
-      if (connection) connection.handleSDP(msg);
+      if (connection) connection.handleSDP(message);
       break;
     case 'CANDIDATE':
-      if (connection) connection.handleCandidate(msg);
+      if (connection) connection.handleCandidate(message);
       break;
     case 'LEAVE':
       if (connection) connection.handleLeave();
       break;
     case 'PORT':
       if (util.browserisms === 'Firefox') {
-        connection.handlePort(msg);
+        connection.handlePort(message);
         break;
       }
     case 'DEFAULT':
-      util.log('Unrecognized message type:', msg.type);
+      util.log('Unrecognized message type:', message.type);
       break;
   }
 };
@@ -229,20 +221,14 @@ Peer.prototype._processQueue = function() {
 
 
 Peer.prototype._cleanup = function() {
-  if (this._socketOpen) {
-    this._socket.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
-  } else {
-    var http = new XMLHttpRequest();
-    http.open('post', this._httpUrl + '/leave', true);
-    http.setRequestHeader('Content-Type', 'application/json');
-    http.send(JSON.stringify({ type: 'LEAVE', src: this._id }));
-  }
-
   for (var peer in this.connections) {
     if (this.connections.hasOwnProperty(peer)) {
       this.connections[peer].close();
     }
   }
+
+  if (this._socketOpen)
+    this._socket.close();
 };
 
 /** Listeners for DataConnection events. */
@@ -257,6 +243,8 @@ Peer.prototype._attachConnectionListeners = function(connection) {
 
 /** Exposed connect function for users. Will try to connect later if user
  * is waiting for an ID. */
+// TODO: pause XHR streaming when not in use and start again when this is
+// called.
 Peer.prototype.connect = function(peer, metadata, cb) {
   if (typeof metadata === 'function' && !cb) cb = metadata; metadata = false;
 
@@ -282,4 +270,3 @@ Peer.prototype.destroy = function() {
 
 
 exports.Peer = Peer;
-

Деякі файли не було показано, через те що забагато файлів було змінено