connection.js 9.4 KB

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