peer.js 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /**
  2. * A peer who can initiate connections with other peers.
  3. */
  4. function Peer(id, options) {
  5. if (id.constructor == Object) {
  6. options = id;
  7. id = undefined;
  8. }
  9. if (!(this instanceof Peer)) return new Peer(options);
  10. EventEmitter.call(this);
  11. options = util.extend({
  12. debug: false,
  13. host: '0.peerjs.com',
  14. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  15. port: 80
  16. }, options);
  17. this._options = options;
  18. util.debug = options.debug;
  19. this._server = options.host + ':' + options.port;
  20. // Ensure alphanumeric_-
  21. if (id && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(id)) {
  22. throw new Error('Peer ID can only contain alphanumerics, "_", and "-".');
  23. }
  24. if (options.key && !/^[A-Za-z0-9]+(?:[ _-][A-Za-z0-9]+)*$/.exec(options.key)) {
  25. throw new Error('API key can only contain alphanumerics, "_", and "-".');
  26. }
  27. this.id = id;
  28. // Not used unless using cloud server.
  29. this._key = options.key;
  30. this._startSocket();
  31. // Connections for this peer.
  32. this.connections = {};
  33. // Queued connections to make.
  34. this._queued = [];
  35. };
  36. util.inherits(Peer, EventEmitter);
  37. Peer.prototype._startSocket = function() {
  38. var self = this;
  39. this._socket = new Socket(this._server, this.id, this._key);
  40. this._socket.on('message', function(data) {
  41. self._handleServerJSONMessage(data);
  42. });
  43. this._socket.on('open', function() {
  44. self._processQueue();
  45. });
  46. this._socket.on('error', function(error) {
  47. util.log(error);
  48. self.emit('error', error);
  49. self.emit('close');
  50. });
  51. this._socket.on('close', function() {
  52. var msg = 'Underlying socket has closed';
  53. util.log('error', msg);
  54. self.emit('error', msg);
  55. self.emit('close');
  56. });
  57. this._socket.start();
  58. }
  59. Peer.prototype._handleServerJSONMessage = function(message) {
  60. var peer = message.src;
  61. var connection = this.connections[peer];
  62. switch (message.type) {
  63. case 'ID':
  64. if (!this.id) {
  65. // If we're just now getting an ID then we may have a queue.
  66. this.id = message.id;
  67. this.emit('open', this.id);
  68. this._processQueue();
  69. }
  70. break;
  71. case 'ERROR':
  72. this.emit('error', message.msg);
  73. util.log(message.msg);
  74. break;
  75. case 'ID-TAKEN':
  76. this.emit('error', 'ID `'+this.id+'` is taken');
  77. this.destroy();
  78. this.emit('close');
  79. break;
  80. case 'OFFER':
  81. var options = {
  82. metadata: message.metadata,
  83. sdp: message.sdp,
  84. config: this._options.config,
  85. };
  86. var connection = new DataConnection(this.id, peer, this._socket, options);
  87. this._attachConnectionListeners(connection);
  88. this.connections[peer] = connection;
  89. this.emit('connection', connection, message.metadata);
  90. break;
  91. case 'EXPIRE':
  92. if (connection) {
  93. connection.close();
  94. connection.emit('Could not connect to peer ' + connection.peer);
  95. }
  96. break;
  97. case 'ANSWER':
  98. if (connection) {
  99. connection.handleSDP(message);
  100. }
  101. break;
  102. case 'CANDIDATE':
  103. if (connection) {
  104. connection.handleCandidate(message);
  105. }
  106. break;
  107. case 'LEAVE':
  108. if (connection) {
  109. connection.handleLeave();
  110. }
  111. break;
  112. case 'PORT':
  113. //if (util.browserisms === 'Firefox') {
  114. // connection.handlePort(message);
  115. // break;
  116. //}
  117. case 'DEFAULT':
  118. util.log('Unrecognized message type:', message.type);
  119. break;
  120. }
  121. };
  122. /** Process queued calls to connect. */
  123. Peer.prototype._processQueue = function() {
  124. while (this._queued.length > 0) {
  125. var cdata = this._queued.pop();
  126. this.connect.apply(this, cdata);
  127. }
  128. };
  129. Peer.prototype._cleanup = function() {
  130. var self = this;
  131. var peers = Object.keys(this.connections);
  132. for (var i = 0, ii = peers.length; i < ii; i++) {
  133. this.connections[peers[i]].close();
  134. }
  135. util.setZeroTimeout(function(){
  136. self._socket.close();
  137. });
  138. };
  139. /** Listeners for DataConnection events. */
  140. Peer.prototype._attachConnectionListeners = function(connection) {
  141. var self = this;
  142. connection.on('close', function(peer) {
  143. if (self.connections[peer]) {
  144. delete self.connections[peer];
  145. }
  146. });
  147. };
  148. /** Exposed connect function for users. Will try to connect later if user
  149. * is waiting for an ID. */
  150. // TODO: pause XHR streaming when not in use and start again when this is
  151. // called.
  152. Peer.prototype.connect = function(peer, metadata, options) {
  153. if (!this.id) {
  154. this._queued.push(Array.prototype.slice.apply(arguments));
  155. return;
  156. }
  157. options = util.extend(options, {
  158. metadata: metadata,
  159. config: this._options.config,
  160. });
  161. var connection = new DataConnection(this.id, peer, this._socket, options);
  162. this._attachConnectionListeners(connection);
  163. this.connections[peer] = connection;
  164. return connection;
  165. };
  166. Peer.prototype.destroy = function() {
  167. this._cleanup();
  168. };
  169. exports.Peer = Peer;