connection.js 8.0 KB

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