connection.js 8.0 KB

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