connectionmanager.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /**
  2. * Manages DataConnections between its peer and one other peer.
  3. * Internally, manages PeerConnection.
  4. */
  5. function ConnectionManager(id, peer, socket, options) {
  6. if (!(this instanceof ConnectionManager)) return new ConnectionManager(id, peer, socket, options);
  7. EventEmitter.call(this);
  8. options = util.extend({
  9. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] }
  10. }, options);
  11. this._options = options;
  12. // PeerConnection is not yet dead.
  13. this.open = true;
  14. this.id = id;
  15. this.peer = peer;
  16. this.pc = null;
  17. // Mapping labels to metadata and serialization.
  18. // label => { metadata: ..., serialization: ..., reliable: ...}
  19. this.labels = {};
  20. // A default label in the event that none are passed in.
  21. this._default = 0;
  22. // DataConnections on this PC.
  23. this.connections = {};
  24. this._queued = [];
  25. this._socket = socket;
  26. if (!!this.id) {
  27. this.initialize();
  28. }
  29. };
  30. util.inherits(ConnectionManager, EventEmitter);
  31. ConnectionManager.prototype.initialize = function(id, socket) {
  32. if (!!id) {
  33. this.id = id;
  34. }
  35. if (!!socket) {
  36. this._socket = socket;
  37. }
  38. // Set up PeerConnection.
  39. this._startPeerConnection();
  40. // Process queued DCs.
  41. this._processQueue();
  42. // Listen for ICE candidates.
  43. this._setupIce();
  44. // Listen for negotiation needed.
  45. // Chrome only **
  46. this._setupNegotiationHandler();
  47. // Listen for data channel.
  48. this._setupDataChannel();
  49. this.initialize = function() { };
  50. };
  51. /** Start a PC. */
  52. ConnectionManager.prototype._startPeerConnection = function() {
  53. util.log('Creating RTCPeerConnection');
  54. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  55. };
  56. /** Add DataChannels to all queued DataConnections. */
  57. ConnectionManager.prototype._processQueue = function() {
  58. var conn = this._queued.pop();
  59. if (!!conn) {
  60. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: false }));
  61. }
  62. };
  63. /** Set up ICE candidate handlers. */
  64. ConnectionManager.prototype._setupIce = function() {
  65. util.log('Listening for ICE candidates.');
  66. var self = this;
  67. this.pc.onicecandidate = function(evt) {
  68. if (evt.candidate) {
  69. util.log('Received ICE candidates.');
  70. self._socket.send({
  71. type: 'CANDIDATE',
  72. payload: {
  73. candidate: evt.candidate
  74. },
  75. dst: self.peer
  76. });
  77. }
  78. };
  79. this.pc.oniceconnectionstatechange = function() {
  80. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  81. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  82. self.close();
  83. }
  84. };
  85. // Fallback for older Chrome impls.
  86. this.pc.onicechange = function() {
  87. if (!!self.pc && self.pc.iceConnectionState === 'disconnected') {
  88. util.log('iceConnectionState is disconnected, closing connections to ' + this.peer);
  89. self.close();
  90. }
  91. };
  92. };
  93. /** Set up onnegotiationneeded. */
  94. ConnectionManager.prototype._setupNegotiationHandler = function() {
  95. var self = this;
  96. util.log('Listening for `negotiationneeded`');
  97. this.pc.onnegotiationneeded = function() {
  98. util.log('`negotiationneeded` triggered');
  99. self._makeOffer();
  100. };
  101. };
  102. /** Set up Data Channel listener. */
  103. ConnectionManager.prototype._setupDataChannel = function() {
  104. var self = this;
  105. util.log('Listening for data channel');
  106. this.pc.ondatachannel = function(evt) {
  107. util.log('Received data channel');
  108. var dc = evt.channel;
  109. var label = dc.label;
  110. // This should not be empty.
  111. var options = self.labels[label] || {};
  112. var connection = new DataConnection(self.peer, dc, options);
  113. self._attachConnectionListeners(connection);
  114. self.connections[label] = connection;
  115. self.emit('connection', connection);
  116. };
  117. };
  118. /** Send an offer. */
  119. ConnectionManager.prototype._makeOffer = function() {
  120. var self = this;
  121. this.pc.createOffer(function(offer) {
  122. util.log('Created offer.');
  123. self.pc.setLocalDescription(offer, function() {
  124. util.log('Set localDescription to offer');
  125. self._socket.send({
  126. type: 'OFFER',
  127. payload: {
  128. sdp: offer,
  129. config: self._options.config,
  130. labels: self.labels
  131. },
  132. dst: self.peer
  133. });
  134. // We can now reset labels because all info has been communicated.
  135. self.labels = {};
  136. }, function(err) {
  137. self.emit('error', err);
  138. util.log('Failed to setLocalDescription, ', err);
  139. });
  140. });
  141. };
  142. /** Create an answer for PC. */
  143. ConnectionManager.prototype._makeAnswer = function() {
  144. var self = this;
  145. this.pc.createAnswer(function(answer) {
  146. util.log('Created answer.');
  147. self.pc.setLocalDescription(answer, function() {
  148. util.log('Set localDescription to answer.');
  149. self._socket.send({
  150. type: 'ANSWER',
  151. payload: {
  152. sdp: answer
  153. },
  154. dst: self.peer
  155. });
  156. }, function(err) {
  157. self.emit('error', err);
  158. util.log('Failed to setLocalDescription, ', err);
  159. });
  160. }, function(err) {
  161. self.emit('error', err);
  162. util.log('Failed to create answer, ', err);
  163. });
  164. };
  165. /** Clean up PC, close related DCs. */
  166. ConnectionManager.prototype._cleanup = function() {
  167. util.log('Cleanup ConnectionManager for ' + this.peer);
  168. if (!!this.pc && (this.pc.readyState !== 'closed' || this.pc.signalingState !== 'closed')) {
  169. this.pc.close();
  170. this.pc = null;
  171. }
  172. var self = this;
  173. this._socket.send({
  174. type: 'LEAVE',
  175. dst: self.peer
  176. });
  177. this.open = false;
  178. this.emit('close');
  179. };
  180. /** Attach connection listeners. */
  181. ConnectionManager.prototype._attachConnectionListeners = function(connection) {
  182. var self = this;
  183. connection.on('close', function() {
  184. if (!!self.connections[connection.label]) {
  185. delete self.connections[connection.label];
  186. }
  187. if (!Object.keys(self.connections).length) {
  188. self._cleanup();
  189. }
  190. });
  191. connection.on('open', function() {
  192. self._lock = false;
  193. self._processQueue();
  194. });
  195. };
  196. /** Handle an SDP. */
  197. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  198. sdp = new RTCSessionDescription(sdp);
  199. var self = this;
  200. this.pc.setRemoteDescription(sdp, function() {
  201. util.log('Set remoteDescription: ' + type);
  202. if (type === 'OFFER') {
  203. self._makeAnswer();
  204. }
  205. }, function(err) {
  206. self.emit('error', err);
  207. util.log('Failed to setRemoteDescription, ', err);
  208. });
  209. };
  210. /** Handle a candidate. */
  211. ConnectionManager.prototype.handleCandidate = function(message) {
  212. var candidate = new RTCIceCandidate(message.candidate);
  213. this.pc.addIceCandidate(candidate);
  214. util.log('Added ICE candidate.');
  215. };
  216. /** Handle peer leaving. */
  217. ConnectionManager.prototype.handleLeave = function() {
  218. util.log('Peer ' + this.peer + ' disconnected.');
  219. this.close();
  220. };
  221. /** Closes manager and all related connections. */
  222. ConnectionManager.prototype.close = function() {
  223. if (!this.open) {
  224. this.emit('error', new Error('Connections to ' + this.peer + 'are already closed.'));
  225. return;
  226. }
  227. var labels = Object.keys(this.connections);
  228. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  229. var label = labels[i];
  230. var connection = this.connections[label];
  231. connection.close();
  232. }
  233. this.connections = null;
  234. this._cleanup();
  235. };
  236. /** Create and returns a DataConnection with the peer with the given label. */
  237. ConnectionManager.prototype.connect = function(options) {
  238. if (!this.open) {
  239. return;
  240. }
  241. options = util.extend({
  242. label: 'peerjs'
  243. }, options);
  244. // Check if label is taken...if so, generate a new label randomly.
  245. while (!!this.connections[options.label]) {
  246. options.label = 'peerjs' + this._default;
  247. this._default += 1;
  248. }
  249. this.labels[options.label] = options;
  250. var dc;
  251. if (!!this.pc && !this._lock) {
  252. dc = this.pc.createDataChannel(options.label, { reliable: false });
  253. }
  254. var connection = new DataConnection(this.peer, dc, options);
  255. this._attachConnectionListeners(connection);
  256. this.connections[options.label] = connection;
  257. if (!this.pc || this._lock) {
  258. this._queued.push(connection);
  259. }
  260. this._lock = true
  261. return [options.label, connection];
  262. };
  263. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  264. ConnectionManager.prototype.update = function(updates) {
  265. var labels = Object.keys(updates);
  266. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  267. var label = labels[i];
  268. this.labels[label] = updates[label];
  269. }
  270. };