peer.js 4.4 KB

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