connection.js 8.2 KB

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