connection.js 8.3 KB

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