connection.js 8.2 KB

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