connection.js 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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. this._dc = this._pc.createDataChannel(this.peer, { reliable: this._options.reliable });
  73. this._configureDataChannel();
  74. } else {
  75. util.log('Listening for data channel');
  76. this._pc.ondatachannel = function(evt) {
  77. util.log('Received data channel');
  78. self._dc = evt.channel;
  79. self._configureDataChannel();
  80. };
  81. }
  82. };
  83. /** Starts a PeerConnection and sets up handlers. */
  84. DataConnection.prototype._startPeerConnection = function() {
  85. util.log('Creating RTCPeerConnection');
  86. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  87. };
  88. /** Takes care of ice handlers. */
  89. DataConnection.prototype._setupIce = function() {
  90. util.log('Listening for ICE candidates');
  91. var self = this;
  92. this._pc.onicecandidate = function(evt) {
  93. if (evt.candidate) {
  94. util.log('Received ICE candidates');
  95. self._socket.send({
  96. type: 'CANDIDATE',
  97. payload: {
  98. candidate: evt.candidate
  99. },
  100. dst: self.peer
  101. });
  102. }
  103. };
  104. };
  105. /*DataConnection.prototype._firefoxPortSetup = function() {
  106. if (!DataConnection.usedPorts) {
  107. DataConnection.usedPorts = [];
  108. }
  109. this.localPort = util.randomPort();
  110. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  111. this.localPort = util.randomPort();
  112. }
  113. this.remotePort = util.randomPort();
  114. while (this.remotePort === this.localPort ||
  115. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  116. this.remotePort = util.randomPort();
  117. }
  118. DataConnection.usedPorts.push(this.remotePort);
  119. DataConnection.usedPorts.push(this.localPort);
  120. }*/
  121. DataConnection.prototype._configureDataChannel = function() {
  122. var self = this;
  123. if (util.browserisms !== 'Webkit') {
  124. this._dc.binaryType = 'arraybuffer';
  125. }
  126. this._dc.onopen = function() {
  127. util.log('Data channel connection success');
  128. self.open = true;
  129. self.emit('open');
  130. };
  131. this._dc.onmessage = function(e) {
  132. self._handleDataMessage(e);
  133. };
  134. this._dc.onclose = function(e) {
  135. self.emit('close');
  136. };
  137. };
  138. /** Decide whether to handle Firefoxisms. */
  139. /*DataConnection.prototype._firefoxAdditional = function() {
  140. var self = this;
  141. getUserMedia({ audio: true, fake: true }, function(s) {
  142. self._pc.addStream(s);
  143. if (self._originator) {
  144. self._makeOffer();
  145. }
  146. }, function(err) { util.log('Could not getUserMedia'); });
  147. };*/
  148. DataConnection.prototype._makeOffer = function() {
  149. var self = this;
  150. this._pc.createOffer(function(offer) {
  151. util.log('Created offer');
  152. self._pc.setLocalDescription(offer, function() {
  153. util.log('Set localDescription to offer');
  154. self._socket.send({
  155. type: 'OFFER',
  156. payload: {
  157. sdp: offer,
  158. serialization: self.serialization,
  159. metadata: self.metadata
  160. },
  161. dst: self.peer
  162. });
  163. }, function(err) {
  164. self.emit('error', err);
  165. util.log('Failed to setLocalDescription, ', err);
  166. });
  167. });
  168. };
  169. /** Create an answer for PC. */
  170. DataConnection.prototype._makeAnswer = function() {
  171. var self = this;
  172. this._pc.createAnswer(function(answer) {
  173. util.log('Created answer');
  174. self._pc.setLocalDescription(answer, function() {
  175. util.log('Set localDescription to answer');
  176. self._socket.send({
  177. type: 'ANSWER',
  178. payload: {
  179. sdp: answer
  180. },
  181. dst: self.peer
  182. });
  183. }, function(err) {
  184. self.emit('error', err);
  185. util.log('Failed to setLocalDescription, ', err)
  186. });
  187. }, function(err) {
  188. self.emit('error', err);
  189. util.log('Failed to create answer, ', err)
  190. });
  191. };
  192. DataConnection.prototype._cleanup = function() {
  193. if (!!this._dc && this._dc.readyState != 'closed') {
  194. this._dc.close();
  195. this._dc = null;
  196. }
  197. if (!!this._pc && this._pc.readyState != 'closed') {
  198. this._pc.close();
  199. this._pc = null;
  200. }
  201. };
  202. // Handles a DataChannel message.
  203. DataConnection.prototype._handleDataMessage = function(e) {
  204. var self = this;
  205. var data = e.data;
  206. var datatype = data.constructor;
  207. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  208. if (datatype === Blob) {
  209. util.blobToArrayBuffer(data, function(ab) {
  210. data = BinaryPack.unpack(ab);
  211. self.emit('data', data);
  212. });
  213. return;
  214. } else if (datatype === ArrayBuffer) {
  215. data = BinaryPack.unpack(data);
  216. } else if (datatype === String) {
  217. var ab = util.binaryStringToArrayBuffer(data);
  218. data = BinaryPack.unpack(ab);
  219. }
  220. } else if (this.serialization === 'json') {
  221. data = JSON.parse(data);
  222. }
  223. this.emit('data', data);
  224. };
  225. /**
  226. * Exposed functionality for users.
  227. */
  228. /** Allows user to close connection. */
  229. DataConnection.prototype.close = function() {
  230. this._cleanup();
  231. var self = this;
  232. if (this.open) {
  233. this._socket.send({
  234. type: 'LEAVE',
  235. dst: self.peer
  236. });
  237. }
  238. this.open = false;
  239. this.emit('close', this.peer);
  240. };
  241. /** Allows user to send data. */
  242. DataConnection.prototype.send = function(data) {
  243. var self = this;
  244. if (this.serialization === 'none') {
  245. this._dc.send(data);
  246. } else if (this.serialization === 'json') {
  247. this._dc.send(JSON.stringify(data));
  248. } else {
  249. var utf8 = (this.serialization === 'binary-utf8');
  250. var blob = BinaryPack.pack(data, utf8);
  251. // DataChannel currently only supports strings.
  252. if (util.browserisms === 'Webkit') {
  253. util.blobToBinaryString(blob, function(str){
  254. self._dc.send(str);
  255. });
  256. } else {
  257. this._dc.send(blob);
  258. }
  259. }
  260. };
  261. DataConnection.prototype.handleSDP = function(sdp, type) {
  262. if (util.browserisms != 'Firefox') {
  263. sdp = new RTCSessionDescription(sdp);
  264. }
  265. var self = this;
  266. this._pc.setRemoteDescription(sdp, function() {
  267. util.log('Set remoteDescription: ' + type);
  268. // Firefoxism
  269. /**if (type === 'ANSWER' && util.browserisms === 'Firefox') {
  270. self._pc.connectDataConnection(self.localPort, self.remotePort);
  271. self._socket.send({
  272. type: 'PORT',
  273. dst: self.peer,
  274. payload: {
  275. remote: self.localPort,
  276. local: self.remotePort
  277. }
  278. });
  279. } else*/ if (type === 'OFFER') {
  280. self._makeAnswer();
  281. }
  282. }, function(err) {
  283. self.emit('error', err);
  284. util.log('Failed to setRemoteDescription, ', err);
  285. });
  286. };
  287. DataConnection.prototype.handleCandidate = function(message) {
  288. var candidate = new RTCIceCandidate(message.candidate);
  289. this._pc.addIceCandidate(candidate);
  290. util.log('Added ice candidate');
  291. };
  292. DataConnection.prototype.handleLeave = function() {
  293. util.log('Peer ' + this.peer + ' disconnected');
  294. this.close();
  295. };
  296. /*
  297. DataConnection.prototype.handlePort = function(message) {
  298. if (!DataConnection.usedPorts) {
  299. DataConnection.usedPorts = [];
  300. }
  301. DataConnection.usedPorts.push(message.local);
  302. DataConnection.usedPorts.push(message.remote);
  303. this._pc.connectDataConnection(message.local, message.remote);
  304. };
  305. */