connectionmanager.js 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  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. var dc = evt.channel;
  85. var label = dc.label;
  86. var options = self.labels[label] || {};
  87. var connection = new DataConnection(dc, options);
  88. self.connections[label] = connection;
  89. self.emit('connection', connection);
  90. };
  91. };
  92. /** Send an offer. */
  93. ConnectionManager.prototype._makeOffer = function() {
  94. var self = this;
  95. this.pc.createOffer(function(offer) {
  96. util.log('Created offer.');
  97. self.pc.setLocalDescription(offer, function() {
  98. util.log('Set localDescription to offer');
  99. self._socket.send({
  100. type: 'OFFER',
  101. payload: {
  102. sdp: offer,
  103. labels: self.labels
  104. },
  105. dst: self.peer
  106. });
  107. // We can now reset labels because all info has been communicated.
  108. self.labels = {};
  109. }, function(err) {
  110. self.emit('error', err);
  111. util.log('Failed to setLocalDescription, ', err);
  112. });
  113. });
  114. };
  115. /** Create an answer for PC. */
  116. ConnectionManager.prototype._makeAnswer = function() {
  117. var self = this;
  118. this.pc.createAnswer(function(answer) {
  119. util.log('Created answer.');
  120. self.pc.setLocalDescription(answer, function() {
  121. util.log('Set localDescription to answer.');
  122. self._socket.send({
  123. type: 'ANSWER',
  124. payload: {
  125. sdp: answer
  126. },
  127. dst: self.peer
  128. });
  129. }, function(err) {
  130. self.emit('error', err);
  131. util.log('Failed to setLocalDescription, ', err);
  132. });
  133. }, function(err) {
  134. self.emit('error', err);
  135. util.log('Failed to create answer, ', err);
  136. });
  137. };
  138. /** Clean up PC, close related DCs. */
  139. ConnectionManager.prototype._cleanup = function() {
  140. util.log('Cleanup ConnectionManager for ' + this.peer);
  141. };
  142. /** Handle an SDP. */
  143. ConnectionManager.prototype.handleSDP = function(sdp, type) {
  144. sdp = new RTCSessionDescription(sdp);
  145. var self = this;
  146. this.pc.setRemoteDescription(sdp, function() {
  147. util.log('Set remoteDescription: ' + type);
  148. if (type === 'OFFER') {
  149. self._makeAnswer();
  150. }
  151. }, function(err) {
  152. self.emit('error', err);
  153. util.log('Failed to setRemoteDescription, ', err);
  154. });
  155. };
  156. /** Handle a candidate. */
  157. ConnectionManager.prototype.handleCandidate = function(message) {
  158. var candidate = new RTCIceCandidate(message.candidate);
  159. this.pc.addIceCandidate(candidate);
  160. util.log('Added ICE candidate.');
  161. };
  162. /** Handle peer leaving. */
  163. ConnectionManager.prototype.handleLeave = function() {
  164. util.log('Peer ' + this.peer + ' disconnected.');
  165. this.close();
  166. };
  167. /** Closes manager and all related connections. */
  168. ConnectionManager.prototype.close = function() {
  169. this._cleanup();
  170. var self = this;
  171. if (this.open) {
  172. this._socket.send({
  173. type: 'LEAVE',
  174. dst: self.peer
  175. });
  176. }
  177. this.open = false;
  178. this.emit('close', this.peer);
  179. };
  180. /** Create and returns a DataConnection with the peer with the given label. */
  181. // TODO: queue in case no ID/PC.
  182. ConnectionManager.prototype.connect = function(label, options) {
  183. options = util.extend({
  184. reliable: false,
  185. serialization: 'binary'
  186. }, options);
  187. this.labels[label] = {
  188. reliable: options.reliable,
  189. serialization: options.serialization,
  190. metadata: options.metadata
  191. };
  192. var connection = new DataConnection(this.pc.createDataChannel(this.peer, { reliable: false }), options);
  193. this.connections[label] = connection;
  194. return connection;
  195. };
  196. /** Updates label:[serialization, reliable, metadata] pairs from offer. */
  197. // TODO: queue in case no ID/PC.
  198. ConnectionManager.prototype.update = function(updates) {
  199. var labels = Object.keys(updates);
  200. for (var i = 0, ii = labels.length; i < ii; i += 1) {
  201. var label = labels[i];
  202. this.labels[label] = updates[label];
  203. }
  204. };