connectionmanager.js 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. // DataConnections on this PC.
  21. this.connections = {};
  22. this._queued = [];
  23. this._socket = socket;
  24. if (!!this.id) {
  25. this.initialize();
  26. }
  27. };
  28. util.inherits(ConnectionManager, EventEmitter);
  29. ConnectionManager.prototype.initialize = function(id, socket) {
  30. if (!!id) {
  31. this.id = id;
  32. }
  33. if (!!socket) {
  34. this._socket = socket;
  35. }
  36. // Set up PeerConnection.
  37. this._startPeerConnection();
  38. // Process queued DCs.
  39. this._processQueue();
  40. // Listen for ICE candidates.
  41. this._setupIce();
  42. // Listen for negotiation needed.
  43. // Chrome only **
  44. this._setupNegotiationHandler();
  45. // Listen for data channel.
  46. this._setupDataChannel();
  47. this.initialize = function() { };
  48. };
  49. /** Start a PC. */
  50. ConnectionManager.prototype._startPeerConnection = function() {
  51. util.log('Creating RTCPeerConnection');
  52. this.pc = new RTCPeerConnection(this._options.config, { optional: [ { RtpDataChannels: true } ]});
  53. };
  54. /** Add DataChannels to all queued DataConnections. */
  55. ConnectionManager.prototype._processQueue = function() {
  56. while (this._queued.length > 0) {
  57. var conn = this._queued.pop();
  58. conn.addDC(this.pc.createDataChannel(conn.label, { reliable: false }));
  59. }
  60. };
  61. /** Set up ICE candidate handlers. */
  62. ConnectionManager.prototype._setupIce = function() {
  63. util.log('Listening for ICE candidates.');
  64. var self = this;
  65. this.pc.onicecandidate = function(evt) {
  66. if (evt.candidate) {
  67. util.log('Received ICE candidates.');
  68. self._socket.send({
  69. type: 'CANDIDATE',
  70. payload: {
  71. candidate: evt.candidate
  72. },
  73. dst: self.peer
  74. });
  75. }
  76. };
  77. };
  78. /** Set up onnegotiationneeded. */
  79. ConnectionManager.prototype._setupNegotiationHandler = function() {
  80. var self = this;
  81. util.log('Listening for `negotiationneeded`');
  82. this.pc.onnegotiationneeded = function() {
  83. util.log('`negotiationneeded` triggered');
  84. self._makeOffer();
  85. };
  86. };
  87. /** Set up Data Channel listener. */
  88. ConnectionManager.prototype._setupDataChannel = function() {
  89. var self = this;
  90. util.log('Listening for data channel');
  91. this.pc.ondatachannel = function(evt) {
  92. util.log('Received data channel');
  93. var dc = evt.channel;
  94. var label = dc.label;
  95. // This should not be empty.
  96. var options = self.labels[label] || {};
  97. var connection = new DataConnection(self.peer, dc, options);
  98. self.connections[label] = connection;
  99. self.emit('connection', connection);
  100. };
  101. };
  102. /** Send an offer. */
  103. ConnectionManager.prototype._makeOffer = function() {
  104. var self = this;
  105. this.pc.createOffer(function(offer) {
  106. util.log('Created offer.');
  107. self.pc.setLocalDescription(offer, function() {
  108. util.log('Set localDescription to offer');
  109. self._socket.send({
  110. type: 'OFFER',
  111. payload: {
  112. sdp: offer,
  113. config: self._options.config,
  114. labels: self.labels
  115. },
  116. dst: self.peer
  117. });
  118. // We can now reset labels because all info has been communicated.
  119. self.labels = {};
  120. }, function(err) {
  121. self.emit('error', err);
  122. util.log('Failed to setLocalDescription, ', err);
  123. });
  124. });
  125. };
  126. /** Create an answer for PC. */
  127. ConnectionManager.prototype._makeAnswer = function() {
  128. var self = this;
  129. this.pc.createAnswer(function(answer) {
  130. util.log('Created answer.');
  131. self.pc.setLocalDescription(answer, function() {
  132. util.log('Set localDescription to answer.');
  133. self._socket.send({
  134. type: 'ANSWER',
  135. payload: {
  136. sdp: answer
  137. },
  138. dst: self.peer
  139. });
  140. }, function(err) {
  141. self.emit('error', err);
  142. util.log('Failed to setLocalDescription, ', err);
  143. });
  144. }, function(err) {
  145. self.emit('error', err);
  146. util.log('Failed to create answer, ', err);
  147. });
  148. };
  149. /** Clean up PC, close related DCs. */
  150. ConnectionManager.prototype._cleanup = function() {
  151. util.log('Cleanup ConnectionManager for ' + this.peer);
  152. };
  153. /** Handle an SDP. */
  154. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  155. sdp = new RTCSessionDescription(sdp);
  156. var self = this;
  157. this.pc.setRemoteDescription(sdp, function() {
  158. util.log('Set remoteDescription: ' + type);
  159. if (type === 'OFFER') {
  160. self._makeAnswer();
  161. }
  162. }, function(err) {
  163. self.emit('error', err);
  164. util.log('Failed to setRemoteDescription, ', err);
  165. });
  166. };
  167. /** Handle a candidate. */
  168. ConnectionManager.prototype.handleCandidate = function(message) {
  169. var candidate = new RTCIceCandidate(message.candidate);
  170. this.pc.addIceCandidate(candidate);
  171. util.log('Added ICE candidate.');
  172. };
  173. /** Handle peer leaving. */
  174. ConnectionManager.prototype.handleLeave = function() {
  175. util.log('Peer ' + this.peer + ' disconnected.');
  176. this.close();
  177. };
  178. /** Closes manager and all related connections. */
  179. ConnectionManager.prototype.close = function() {
  180. this._cleanup();
  181. var self = this;
  182. if (this.open) {
  183. this._socket.send({
  184. type: 'LEAVE',
  185. dst: self.peer
  186. });
  187. }
  188. this.open = false;
  189. this.emit('close', this.peer);
  190. };
  191. /** Create and returns a DataConnection with the peer with the given label. */
  192. ConnectionManager.prototype.connect = function(label, options) {
  193. // Check if label is taken.
  194. if (!!this.connections[label]) {
  195. this.emit('error', new Error('Label name taken for peer: ' + this.peer));
  196. return;
  197. }
  198. options = util.extend({
  199. reliable: false,
  200. serialization: 'binary',
  201. label: label
  202. }, options);
  203. this.labels[label] = options;
  204. var dc;
  205. if (!!this.pc) {
  206. dc = this.pc.createDataChannel(label, { reliable: false });
  207. }
  208. var connection = new DataConnection(this.peer, dc, options);
  209. this.connections[label] = connection;
  210. if (!this.pc) {
  211. this._queued.push(connection);
  212. }
  213. return connection;
  214. };
  215. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  216. ConnectionManager.prototype.update = function(updates) {
  217. var labels = Object.keys(updates);
  218. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  219. var label = labels[i];
  220. this.labels[label] = updates[label];
  221. }
  222. };