connection.js 9.7 KB

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