connection.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. /**
  2. * A DataChannel PeerConnection between two Peers.
  3. */
  4. function DataConnection(id, peer, socket, options) {
  5. if (!(this instanceof DataConnection)) return new DataConnection(options);
  6. EventEmitter.call(this);
  7. options = util.extend({
  8. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  9. reliable: false
  10. }, options);
  11. this._options = options;
  12. // Connection is not open yet
  13. this.open = false;
  14. this.id = id;
  15. this.peer = peer;
  16. this.metadata = options.metadata;
  17. this._originator = (options.sdp === undefined);
  18. this._socket = socket;
  19. this._sdp = options.sdp;
  20. // TODO: consider no-oping this method:
  21. if (!!this.id) {
  22. this.initialize();
  23. }
  24. };
  25. util.inherits(DataConnection, EventEmitter);
  26. DataConnection.prototype.initialize = function(id) {
  27. if (!!id) {
  28. this.id = id;
  29. }
  30. // Firefoxism: connectDataConnection ports.
  31. /*if (util.browserisms === 'Firefox') {
  32. this._firefoxPortSetup();
  33. }*/
  34. // Set up PeerConnection.
  35. this._startPeerConnection();
  36. // Listen for ICE candidates
  37. this._setupIce();
  38. // Listen for negotiation needed
  39. // ** Chrome only.
  40. if (util.browserisms !== 'Firefox' && !!this.id) {
  41. this._setupOffer();
  42. }
  43. // Listen or create a data channel
  44. this._setupDataChannel();
  45. var self = this;
  46. if (this._sdp) {
  47. this.handleSDP({ type: 'OFFER', sdp: this._sdp });
  48. }
  49. // Makes offer if Firefox
  50. /*if (util.browserisms === 'Firefox') {
  51. this._firefoxAdditional();
  52. }*/
  53. // No-op this.
  54. this.initialize = function() {};
  55. }
  56. DataConnection.prototype._setupOffer = function() {
  57. var self = this;
  58. util.log('Listening for `negotiationneeded`');
  59. this._pc.onnegotiationneeded = function() {
  60. util.log('`negotiationneeded` triggered');
  61. self._makeOffer();
  62. };
  63. }
  64. DataConnection.prototype._setupDataChannel = function() {
  65. var self = this;
  66. if (this._originator) {
  67. util.log('Creating data channel');
  68. this._dc = this._pc.createDataChannel(this.peer, { reliable: this._options.reliable });
  69. this._configureDataChannel();
  70. } else {
  71. util.log('Listening for data channel');
  72. this._pc.ondatachannel = function(evt) {
  73. util.log('Received data channel');
  74. self._dc = evt.channel;
  75. self._configureDataChannel();
  76. };
  77. }
  78. };
  79. /** Starts a PeerConnection and sets up handlers. */
  80. DataConnection.prototype._startPeerConnection = function() {
  81. util.log('Creating RTCPeerConnection');
  82. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  83. };
  84. /** Takes care of ice handlers. */
  85. DataConnection.prototype._setupIce = function() {
  86. util.log('Listening for ICE candidates');
  87. var self = this;
  88. this._pc.onicecandidate = function(evt) {
  89. if (evt.candidate) {
  90. util.log('Received ICE candidates');
  91. self._socket.send({
  92. type: 'CANDIDATE',
  93. candidate: evt.candidate,
  94. dst: self.peer,
  95. src: self.id
  96. });
  97. }
  98. };
  99. };
  100. /*DataConnection.prototype._firefoxPortSetup = function() {
  101. if (!DataConnection.usedPorts) {
  102. DataConnection.usedPorts = [];
  103. }
  104. this.localPort = util.randomPort();
  105. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  106. this.localPort = util.randomPort();
  107. }
  108. this.remotePort = util.randomPort();
  109. while (this.remotePort === this.localPort ||
  110. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  111. this.remotePort = util.randomPort();
  112. }
  113. DataConnection.usedPorts.push(this.remotePort);
  114. DataConnection.usedPorts.push(this.localPort);
  115. }*/
  116. DataConnection.prototype._configureDataChannel = function() {
  117. var self = this;
  118. if (util.browserisms !== 'Webkit') {
  119. this._dc.binaryType = 'arraybuffer';
  120. }
  121. this._dc.onopen = function() {
  122. util.log('Data channel connection success');
  123. self.open = true;
  124. self.emit('open');
  125. };
  126. this._dc.onmessage = function(e) {
  127. self._handleDataMessage(e);
  128. };
  129. };
  130. /** Decide whether to handle Firefoxisms. */
  131. /*DataConnection.prototype._firefoxAdditional = function() {
  132. var self = this;
  133. getUserMedia({ audio: true, fake: true }, function(s) {
  134. self._pc.addStream(s);
  135. if (self._originator) {
  136. self._makeOffer();
  137. }
  138. }, function(err) { util.log('Could not getUserMedia'); });
  139. };*/
  140. DataConnection.prototype._makeOffer = function() {
  141. var self = this;
  142. this._pc.createOffer(function(offer) {
  143. util.log('Created offer');
  144. self._pc.setLocalDescription(offer, function() {
  145. util.log('Set localDescription to offer');
  146. self._socket.send({
  147. type: 'OFFER',
  148. sdp: offer,
  149. dst: self.peer,
  150. src: self.id,
  151. metadata: self.metadata
  152. });
  153. }, function(err) {
  154. self.emit('error', 'Failed to setLocalDescription');
  155. util.log('Failed to setLocalDescription, ', err);
  156. });
  157. });
  158. };
  159. /** Create an answer for PC. */
  160. DataConnection.prototype._makeAnswer = function() {
  161. var self = this;
  162. this._pc.createAnswer(function(answer) {
  163. util.log('Created answer');
  164. self._pc.setLocalDescription(answer, function() {
  165. util.log('Set localDescription to answer');
  166. self._socket.send({
  167. type: 'ANSWER',
  168. src: self.id,
  169. sdp: answer,
  170. dst: self.peer
  171. });
  172. }, function(err) {
  173. self.emit('error', 'Failed to setLocalDescription');
  174. util.log('Failed to setLocalDescription, ', err)
  175. });
  176. }, function(err) {
  177. self.emit('error', 'Failed to create answer');
  178. util.log('Failed to create answer, ', err)
  179. });
  180. };
  181. DataConnection.prototype._cleanup = function() {
  182. if (!!this._dc && this._dc.readyState != 'closed') {
  183. this._dc.close();
  184. this._dc = null;
  185. }
  186. if (!!this._pc && this._pc.readyState != 'closed') {
  187. this._pc.close();
  188. this._pc = null;
  189. }
  190. };
  191. // Handles a DataChannel message.
  192. DataConnection.prototype._handleDataMessage = function(e) {
  193. var self = this;
  194. if (e.data.constructor === Blob) {
  195. util.blobToArrayBuffer(e.data, function(ab) {
  196. var data = BinaryPack.unpack(ab);
  197. self.emit('data', data);
  198. });
  199. } else if (e.data.constructor === ArrayBuffer) {
  200. var data = BinaryPack.unpack(e.data);
  201. self.emit('data', data);
  202. } else if (e.data.constructor === String) {
  203. var ab = util.binaryStringToArrayBuffer(e.data);
  204. var data = BinaryPack.unpack(ab);
  205. self.emit('data', data);
  206. }
  207. };
  208. /**
  209. * Exposed functionality for users.
  210. */
  211. /** Allows user to close connection. */
  212. DataConnection.prototype.close = function() {
  213. this._cleanup();
  214. var self = this;
  215. if (this.open) {
  216. this._socket.send({
  217. type: 'LEAVE',
  218. dst: self.peer,
  219. src: self.id,
  220. });
  221. }
  222. this.open = false;
  223. this.emit('close', this.peer);
  224. };
  225. /** Allows user to send data. */
  226. DataConnection.prototype.send = function(data) {
  227. var self = this;
  228. var blob = BinaryPack.pack(data);
  229. if (util.browserisms === 'Webkit') {
  230. util.blobToBinaryString(blob, function(str){
  231. self._dc.send(str);
  232. });
  233. } else {
  234. this._dc.send(blob);
  235. }
  236. };
  237. DataConnection.prototype.handleSDP = function(message) {
  238. var sdp = message.sdp;
  239. if (util.browserisms != 'Firefox') {
  240. sdp = new RTCSessionDescription(sdp);
  241. }
  242. var self = this;
  243. this._pc.setRemoteDescription(sdp, function() {
  244. util.log('Set remoteDescription: ' + message.type);
  245. // Firefoxism
  246. if (message.type === 'ANSWER' && util.browserisms === 'Firefox') {
  247. self._pc.connectDataConnection(self.localPort, self.remotePort);
  248. self._socket.send({
  249. type: 'PORT',
  250. dst: self.peer,
  251. src: self.id,
  252. remote: self.localPort,
  253. local: self.remotePort
  254. });
  255. } else if (message.type === 'OFFER') {
  256. self._makeAnswer();
  257. }
  258. }, function(err) {
  259. self.emit('error', 'Failed to setRemoteDescription');
  260. util.log('Failed to setRemoteDescription, ', err);
  261. });
  262. };
  263. DataConnection.prototype.handleCandidate = function(message) {
  264. var candidate = new RTCIceCandidate(message.candidate);
  265. this._pc.addIceCandidate(candidate);
  266. util.log('Added ice candidate');
  267. };
  268. DataConnection.prototype.handleLeave = function() {
  269. util.log('Peer ' + this.peer + ' disconnected');
  270. this.close();
  271. };
  272. /*
  273. DataConnection.prototype.handlePort = function(message) {
  274. if (!DataConnection.usedPorts) {
  275. DataConnection.usedPorts = [];
  276. }
  277. DataConnection.usedPorts.push(message.local);
  278. DataConnection.usedPorts.push(message.remote);
  279. this._pc.connectDataConnection(message.local, message.remote);
  280. };
  281. */