connection.js 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. /**
  2. * A DataChannel PeerConnection between two Peers.
  3. */
  4. function DataConnection(id, peer, socket, cb, 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._originator = (options.sdp === undefined);
  17. this._cb = cb;
  18. this._metadata = options.metadata;
  19. this._socket = socket;
  20. // Firefoxism: connectDataConnection ports.
  21. /*if (util.browserisms === 'Firefox') {
  22. this._firefoxPortSetup();
  23. }*/
  24. // Set up PeerConnection.
  25. this._startPeerConnection();
  26. // Listen for ICE candidates
  27. this._setupIce();
  28. // Listen for negotiation needed
  29. // ** Chrome only.
  30. if (util.browserisms !== 'Firefox') {
  31. this._setupOffer();
  32. }
  33. // Listen or create a data channel
  34. this._setupDataChannel();
  35. var self = this;
  36. if (options.sdp) {
  37. this.handleSDP({ type: 'OFFER', sdp: options.sdp });
  38. }
  39. // Makes offer if Firefox
  40. /*if (util.browserisms === 'Firefox') {
  41. this._firefoxAdditional();
  42. }*/
  43. };
  44. util.inherits(DataConnection, EventEmitter);
  45. DataConnection.prototype._setupOffer = function() {
  46. var self = this;
  47. util.log('Listening for `negotiationneeded`');
  48. this._pc.onnegotiationneeded = function() {
  49. util.log('`negotiationneeded` triggered');
  50. self._makeOffer();
  51. };
  52. }
  53. DataConnection.prototype._setupDataChannel = function() {
  54. var self = this;
  55. if (this._originator) {
  56. util.log('Creating data channel');
  57. this._dc = this._pc.createDataChannel(this._peer, { reliable: this._options.reliable });
  58. this._configureDataChannel();
  59. } else {
  60. util.log('Listening for data channel');
  61. this._pc.ondatachannel = function(evt) {
  62. util.log('Received data channel');
  63. self._dc = evt.channel;
  64. self._configureDataChannel();
  65. };
  66. }
  67. };
  68. /** Starts a PeerConnection and sets up handlers. */
  69. DataConnection.prototype._startPeerConnection = function() {
  70. util.log('Creating RTCPeerConnection');
  71. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  72. };
  73. /** Takes care of ice handlers. */
  74. DataConnection.prototype._setupIce = function() {
  75. util.log('Listening for ICE candidates');
  76. var self = this;
  77. this._pc.onicecandidate = function(evt) {
  78. if (evt.candidate) {
  79. util.log('Received ICE candidates');
  80. self._socket.send({
  81. type: 'CANDIDATE',
  82. candidate: evt.candidate,
  83. dst: self._peer,
  84. src: self._id
  85. });
  86. }
  87. };
  88. };
  89. /*DataConnection.prototype._firefoxPortSetup = function() {
  90. if (!DataConnection.usedPorts) {
  91. DataConnection.usedPorts = [];
  92. }
  93. this.localPort = util.randomPort();
  94. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  95. this.localPort = util.randomPort();
  96. }
  97. this.remotePort = util.randomPort();
  98. while (this.remotePort === this.localPort ||
  99. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  100. this.remotePort = util.randomPort();
  101. }
  102. DataConnection.usedPorts.push(this.remotePort);
  103. DataConnection.usedPorts.push(this.localPort);
  104. }*/
  105. DataConnection.prototype._configureDataChannel = function() {
  106. var self = this;
  107. if (util.browserisms !== 'Webkit') {
  108. this._dc.binaryType = 'arraybuffer';
  109. }
  110. this._dc.onopen = function() {
  111. util.log('Data channel connection success');
  112. self.open = true;
  113. self._callback(null, self);
  114. };
  115. this._dc.onmessage = function(e) {
  116. self._handleDataMessage(e);
  117. };
  118. };
  119. /** Decide whether to handle Firefoxisms. */
  120. /*DataConnection.prototype._firefoxAdditional = function() {
  121. var self = this;
  122. getUserMedia({ audio: true, fake: true }, function(s) {
  123. self._pc.addStream(s);
  124. if (self._originator) {
  125. self._makeOffer();
  126. }
  127. }, function(err) { util.log('Could not getUserMedia'); });
  128. };*/
  129. DataConnection.prototype._makeOffer = function() {
  130. var self = this;
  131. this._pc.createOffer(function(offer) {
  132. util.log('Created offer');
  133. self._pc.setLocalDescription(offer, function() {
  134. util.log('Set localDescription to offer');
  135. //self._peerReady = false;
  136. self._socket.send({
  137. type: 'OFFER',
  138. sdp: offer,
  139. dst: self._peer,
  140. src: self._id,
  141. metadata: self.metadata
  142. });
  143. }, function(err) {
  144. self._callback('Failed to setLocalDescription');
  145. util.log('Failed to setLocalDescription, ', err);
  146. });
  147. });
  148. };
  149. /** Create an answer for PC. */
  150. DataConnection.prototype._makeAnswer = function() {
  151. var self = this;
  152. this._pc.createAnswer(function(answer) {
  153. util.log('Created answer');
  154. self._pc.setLocalDescription(answer, function() {
  155. util.log('Set localDescription to answer');
  156. self._socket.send({
  157. type: 'ANSWER',
  158. src: self._id,
  159. sdp: answer,
  160. dst: self._peer
  161. });
  162. }, function(err) {
  163. self._callback('Failed to setLocalDescription');
  164. util.log('Failed to setLocalDescription, ', err)
  165. });
  166. }, function(err) {
  167. self._callback('Failed to create answer');
  168. util.log('Failed to create answer, ', err)
  169. });
  170. };
  171. DataConnection.prototype._cleanup = function() {
  172. if (!!this._dc && this._dc.readyState != 'closed') {
  173. this._dc.close();
  174. this._dc = null;
  175. }
  176. if (!!this._pc && this._pc.readyState != 'closed') {
  177. this._pc.close();
  178. this._pc = null;
  179. }
  180. this.emit('close', this._peer);
  181. };
  182. // Make sure _cb only gets called once
  183. DataConnection.prototype._callback = function(err, dc) {
  184. if (this._cb) {
  185. this._cb(err, dc);
  186. delete this._cb;
  187. }
  188. }
  189. // Handles a DataChannel message.
  190. DataConnection.prototype._handleDataMessage = function(e) {
  191. var self = this;
  192. if (e.data.constructor === Blob) {
  193. util.blobToArrayBuffer(e.data, function(ab) {
  194. var data = BinaryPack.unpack(ab);
  195. self.emit('data', data);
  196. });
  197. } else if (e.data.constructor === ArrayBuffer) {
  198. var data = BinaryPack.unpack(e.data);
  199. self.emit('data', data);
  200. } else if (e.data.constructor === String) {
  201. var ab = util.binaryStringToArrayBuffer(e.data);
  202. var data = BinaryPack.unpack(ab);
  203. self.emit('data', data);
  204. }
  205. };
  206. /**
  207. * Exposed functionality for users.
  208. */
  209. /** Allows user to close connection. */
  210. DataConnection.prototype.close = function(reason) {
  211. this._cleanup();
  212. var self = this;
  213. if (this.open) {
  214. this._socket.send({
  215. type: 'LEAVE',
  216. dst: self._peer,
  217. src: self._id,
  218. });
  219. } else {
  220. this._callback(reason);
  221. }
  222. this.open = false;
  223. };
  224. /** Allows user to send data. */
  225. DataConnection.prototype.send = function(data) {
  226. var self = this;
  227. var blob = BinaryPack.pack(data);
  228. if (util.browserisms === 'Webkit') {
  229. util.blobToBinaryString(blob, function(str){
  230. self._dc.send(str);
  231. });
  232. } else {
  233. this._dc.send(blob);
  234. }
  235. };
  236. DataConnection.prototype.getMetadata = function() {
  237. return this._metadata;
  238. };
  239. DataConnection.prototype.handleSDP = function(message) {
  240. var sdp = message.sdp;
  241. if (util.browserisms != 'Firefox') {
  242. sdp = new RTCSessionDescription(sdp);
  243. }
  244. var self = this;
  245. this._pc.setRemoteDescription(sdp, function() {
  246. util.log('Set remoteDescription: ' + message.type);
  247. // Firefoxism
  248. if (message.type === 'ANSWER' && util.browserisms === 'Firefox') {
  249. self._pc.connectDataConnection(self.localPort, self.remotePort);
  250. self._socket.send({
  251. type: 'PORT',
  252. dst: self._peer,
  253. src: self._id,
  254. remote: self.localPort,
  255. local: self.remotePort
  256. });
  257. } else if (message.type === 'OFFER') {
  258. self._makeAnswer();
  259. }
  260. }, function(err) {
  261. self._callback('Failed to setRemoteDescription');
  262. util.log('Failed to setRemoteDescription, ', err);
  263. });
  264. };
  265. DataConnection.prototype.handleCandidate = function(message) {
  266. var candidate = new RTCIceCandidate(message.candidate);
  267. this._pc.addIceCandidate(candidate);
  268. util.log('Added ice candidate');
  269. };
  270. DataConnection.prototype.handleLeave = function() {
  271. util.log('Peer ' + this._peer + ' disconnected');
  272. this._cleanup();
  273. };
  274. /*
  275. DataConnection.prototype.handlePort = function(message) {
  276. if (!DataConnection.usedPorts) {
  277. DataConnection.usedPorts = [];
  278. }
  279. DataConnection.usedPorts.push(message.local);
  280. DataConnection.usedPorts.push(message.remote);
  281. this._pc.connectDataConnection(message.local, message.remote);
  282. };
  283. */