connection.js 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373
  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. 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);
  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);
  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. };
  140. if (this._reliable) {
  141. this._reliable.onmessage = function(msg) {
  142. self.emit('data', msg);
  143. };
  144. } else {
  145. this._dc.onmessage = function(e) {
  146. self._handleDataMessage(e);
  147. };
  148. }
  149. this._dc.onclose = function(e) {
  150. self.emit('close');
  151. };
  152. };
  153. /** Decide whether to handle Firefoxisms. */
  154. /*DataConnection.prototype._firefoxAdditional = function() {
  155. var self = this;
  156. getUserMedia({ audio: true, fake: true }, function(s) {
  157. self._pc.addStream(s);
  158. if (self._originator) {
  159. self._makeOffer();
  160. }
  161. }, function(err) { util.log('Could not getUserMedia'); });
  162. };*/
  163. DataConnection.prototype._makeOffer = function() {
  164. var self = this;
  165. this._pc.createOffer(function(offer) {
  166. util.log('Created offer');
  167. self._pc.setLocalDescription(offer, function() {
  168. util.log('Set localDescription to offer');
  169. self._socket.send({
  170. type: 'OFFER',
  171. payload: {
  172. sdp: offer,
  173. serialization: self.serialization,
  174. metadata: self.metadata,
  175. reliable: self._options.reliable
  176. },
  177. dst: self.peer
  178. });
  179. }, function(err) {
  180. self.emit('error', err);
  181. util.log('Failed to setLocalDescription, ', err);
  182. });
  183. });
  184. };
  185. /** Create an answer for PC. */
  186. DataConnection.prototype._makeAnswer = function() {
  187. var self = this;
  188. this._pc.createAnswer(function(answer) {
  189. util.log('Created answer');
  190. self._pc.setLocalDescription(answer, function() {
  191. util.log('Set localDescription to answer');
  192. self._socket.send({
  193. type: 'ANSWER',
  194. payload: {
  195. sdp: answer
  196. },
  197. dst: self.peer
  198. });
  199. }, function(err) {
  200. self.emit('error', err);
  201. util.log('Failed to setLocalDescription, ', err)
  202. });
  203. }, function(err) {
  204. self.emit('error', err);
  205. util.log('Failed to create answer, ', err)
  206. });
  207. };
  208. DataConnection.prototype._cleanup = function() {
  209. if (!!this._dc && this._dc.readyState != 'closed') {
  210. this._dc.close();
  211. this._dc = null;
  212. }
  213. if (!!this._pc && this._pc.readyState != 'closed') {
  214. this._pc.close();
  215. this._pc = null;
  216. }
  217. };
  218. // Handles a DataChannel message.
  219. DataConnection.prototype._handleDataMessage = function(e) {
  220. var self = this;
  221. var data = e.data;
  222. var datatype = data.constructor;
  223. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  224. if (datatype === Blob) {
  225. util.blobToArrayBuffer(data, function(ab) {
  226. data = util.unpack(ab);
  227. self.emit('data', data);
  228. });
  229. return;
  230. } else if (datatype === ArrayBuffer) {
  231. data = util.unpack(data);
  232. } else if (datatype === String) {
  233. var ab = util.binaryStringToArrayBuffer(data);
  234. data = util.unpack(ab);
  235. }
  236. } else if (this.serialization === 'json') {
  237. data = JSON.parse(data);
  238. }
  239. this.emit('data', data);
  240. };
  241. /**
  242. * Exposed functionality for users.
  243. */
  244. /** Allows user to close connection. */
  245. DataConnection.prototype.close = function() {
  246. this._cleanup();
  247. var self = this;
  248. if (this.open) {
  249. this._socket.send({
  250. type: 'LEAVE',
  251. dst: self.peer
  252. });
  253. }
  254. this.open = false;
  255. this.emit('close', this.peer);
  256. };
  257. /** Allows user to send data. */
  258. DataConnection.prototype.send = function(data) {
  259. if (this._reliable) {
  260. // Note: reliable sending will make it so that you cannot customize
  261. // serialization.
  262. this._reliable.send(data);
  263. return;
  264. }
  265. var self = this;
  266. if (this.serialization === 'none') {
  267. this._dc.send(data);
  268. } else if (this.serialization === 'json') {
  269. this._dc.send(JSON.stringify(data));
  270. } else {
  271. var utf8 = (this.serialization === 'binary-utf8');
  272. var blob = util.pack(data, utf8);
  273. // DataChannel currently only supports strings.
  274. if (util.browserisms === 'Webkit') {
  275. util.blobToBinaryString(blob, function(str){
  276. self._dc.send(str);
  277. });
  278. } else {
  279. this._dc.send(blob);
  280. }
  281. }
  282. };
  283. DataConnection.prototype.handleSDP = function(sdp, type) {
  284. if (util.browserisms != 'Firefox') {
  285. sdp = new RTCSessionDescription(sdp);
  286. }
  287. var self = this;
  288. this._pc.setRemoteDescription(sdp, function() {
  289. util.log('Set remoteDescription: ' + type);
  290. // Firefoxism
  291. /**if (type === 'ANSWER' && util.browserisms === 'Firefox') {
  292. self._pc.connectDataConnection(self.localPort, self.remotePort);
  293. self._socket.send({
  294. type: 'PORT',
  295. dst: self.peer,
  296. payload: {
  297. remote: self.localPort,
  298. local: self.remotePort
  299. }
  300. });
  301. } else*/ if (type === 'OFFER') {
  302. self._makeAnswer();
  303. }
  304. }, function(err) {
  305. self.emit('error', err);
  306. util.log('Failed to setRemoteDescription, ', err);
  307. });
  308. };
  309. DataConnection.prototype.handleCandidate = function(message) {
  310. var candidate = new RTCIceCandidate(message.candidate);
  311. this._pc.addIceCandidate(candidate);
  312. util.log('Added ice candidate');
  313. };
  314. DataConnection.prototype.handleLeave = function() {
  315. util.log('Peer ' + this.peer + ' disconnected');
  316. this.close();
  317. };
  318. /*
  319. DataConnection.prototype.handlePort = function(message) {
  320. if (!DataConnection.usedPorts) {
  321. DataConnection.usedPorts = [];
  322. }
  323. DataConnection.usedPorts.push(message.local);
  324. DataConnection.usedPorts.push(message.remote);
  325. this._pc.connectDataConnection(message.local, message.remote);
  326. };
  327. */