connectionmanager.js 6.1 KB

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