connection.js 8.3 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._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. this._dc.onclose = function(e) {
  130. self.emit('close');
  131. };
  132. };
  133. /** Decide whether to handle Firefoxisms. */
  134. /*DataConnection.prototype._firefoxAdditional = function() {
  135. var self = this;
  136. getUserMedia({ audio: true, fake: true }, function(s) {
  137. self._pc.addStream(s);
  138. if (self._originator) {
  139. self._makeOffer();
  140. }
  141. }, function(err) { util.log('Could not getUserMedia'); });
  142. };*/
  143. DataConnection.prototype._makeOffer = function() {
  144. var self = this;
  145. this._pc.createOffer(function(offer) {
  146. util.log('Created offer');
  147. self._pc.setLocalDescription(offer, function() {
  148. util.log('Set localDescription to offer');
  149. self._socket.send({
  150. type: 'OFFER',
  151. sdp: offer,
  152. dst: self.peer,
  153. src: self.id,
  154. metadata: self.metadata
  155. });
  156. }, function(err) {
  157. self.emit('error', 'Failed to setLocalDescription');
  158. util.log('Failed to setLocalDescription, ', err);
  159. });
  160. });
  161. };
  162. /** Create an answer for PC. */
  163. DataConnection.prototype._makeAnswer = function() {
  164. var self = this;
  165. this._pc.createAnswer(function(answer) {
  166. util.log('Created answer');
  167. self._pc.setLocalDescription(answer, function() {
  168. util.log('Set localDescription to answer');
  169. self._socket.send({
  170. type: 'ANSWER',
  171. src: self.id,
  172. sdp: answer,
  173. dst: self.peer
  174. });
  175. }, function(err) {
  176. self.emit('error', 'Failed to setLocalDescription');
  177. util.log('Failed to setLocalDescription, ', err)
  178. });
  179. }, function(err) {
  180. self.emit('error', 'Failed to create answer');
  181. util.log('Failed to create answer, ', err)
  182. });
  183. };
  184. DataConnection.prototype._cleanup = function() {
  185. if (!!this._dc && this._dc.readyState != 'closed') {
  186. this._dc.close();
  187. this._dc = null;
  188. }
  189. if (!!this._pc && this._pc.readyState != 'closed') {
  190. this._pc.close();
  191. this._pc = null;
  192. }
  193. };
  194. // Handles a DataChannel message.
  195. DataConnection.prototype._handleDataMessage = function(e) {
  196. var self = this;
  197. if (e.data.constructor === Blob) {
  198. util.blobToArrayBuffer(e.data, function(ab) {
  199. var data = BinaryPack.unpack(ab);
  200. self.emit('data', data);
  201. });
  202. } else if (e.data.constructor === ArrayBuffer) {
  203. var data = BinaryPack.unpack(e.data);
  204. self.emit('data', data);
  205. } else if (e.data.constructor === String) {
  206. var ab = util.binaryStringToArrayBuffer(e.data);
  207. var data = BinaryPack.unpack(ab);
  208. self.emit('data', data);
  209. }
  210. };
  211. /**
  212. * Exposed functionality for users.
  213. */
  214. /** Allows user to close connection. */
  215. DataConnection.prototype.close = function() {
  216. this._cleanup();
  217. var self = this;
  218. if (this.open) {
  219. this._socket.send({
  220. type: 'LEAVE',
  221. dst: self.peer,
  222. src: self.id,
  223. });
  224. }
  225. this.open = false;
  226. this.emit('close', this.peer);
  227. };
  228. /** Allows user to send data. */
  229. DataConnection.prototype.send = function(data) {
  230. var self = this;
  231. var blob = BinaryPack.pack(data);
  232. if (util.browserisms === 'Webkit') {
  233. util.blobToBinaryString(blob, function(str){
  234. self._dc.send(str);
  235. });
  236. } else {
  237. this._dc.send(blob);
  238. }
  239. };
  240. DataConnection.prototype.handleSDP = function(message) {
  241. var sdp = message.sdp;
  242. if (util.browserisms != 'Firefox') {
  243. sdp = new RTCSessionDescription(sdp);
  244. }
  245. var self = this;
  246. this._pc.setRemoteDescription(sdp, function() {
  247. util.log('Set remoteDescription: ' + message.type);
  248. // Firefoxism
  249. if (message.type === 'ANSWER' && util.browserisms === 'Firefox') {
  250. self._pc.connectDataConnection(self.localPort, self.remotePort);
  251. self._socket.send({
  252. type: 'PORT',
  253. dst: self.peer,
  254. src: self.id,
  255. remote: self.localPort,
  256. local: self.remotePort
  257. });
  258. } else if (message.type === 'OFFER') {
  259. self._makeAnswer();
  260. }
  261. }, function(err) {
  262. self.emit('error', 'Failed to setRemoteDescription');
  263. util.log('Failed to setRemoteDescription, ', err);
  264. });
  265. };
  266. DataConnection.prototype.handleCandidate = function(message) {
  267. var candidate = new RTCIceCandidate(message.candidate);
  268. this._pc.addIceCandidate(candidate);
  269. util.log('Added ice candidate');
  270. };
  271. DataConnection.prototype.handleLeave = function() {
  272. util.log('Peer ' + this.peer + ' disconnected');
  273. this.close();
  274. };
  275. /*
  276. DataConnection.prototype.handlePort = function(message) {
  277. if (!DataConnection.usedPorts) {
  278. DataConnection.usedPorts = [];
  279. }
  280. DataConnection.usedPorts.push(message.local);
  281. DataConnection.usedPorts.push(message.remote);
  282. this._pc.connectDataConnection(message.local, message.remote);
  283. };
  284. */