connection.js 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  1. /**
  2. * Wraps a DataChannel between two Peers.
  3. */
  4. function DataConnection(id, peer, socket, options) {
  5. if (!(this instanceof DataConnection)) return new DataConnection(id, peer, socket, options);
  6. EventEmitter.call(this);
  7. options = util.extend({
  8. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  9. reliable: false,
  10. serialization: 'binary'
  11. }, options);
  12. this._options = options;
  13. // Connection is not open yet.
  14. this.open = false;
  15. this.id = id;
  16. this.peer = peer;
  17. this.metadata = options.metadata;
  18. this.serialization = options.serialization;
  19. this._originator = (options.sdp === undefined);
  20. this._socket = socket;
  21. this._sdp = options.sdp;
  22. if (!!this.id) {
  23. this.initialize();
  24. }
  25. };
  26. util.inherits(DataConnection, EventEmitter);
  27. DataConnection.prototype.initialize = function(id, socket) {
  28. if (!!id) {
  29. this.id = id;
  30. }
  31. if (!!socket) {
  32. this._socket = socket;
  33. }
  34. // Set up PeerConnection.
  35. this._startPeerConnection();
  36. // Listen for ICE candidates
  37. this._setupIce();
  38. // Listen for negotiation needed
  39. // ** Chrome only.
  40. if (util.browserisms !== 'Firefox' && !!this.id) {
  41. this._setupOffer();
  42. }
  43. // Listen for or create a data channel
  44. this._setupDataChannel();
  45. var self = this;
  46. if (!!this._sdp) {
  47. this.handleSDP(this._sdp, 'OFFER');
  48. }
  49. // No-op this.
  50. this.initialize = function() {};
  51. };
  52. DataConnection.prototype._setupOffer = function() {
  53. var self = this;
  54. util.log('Listening for `negotiationneeded`');
  55. this._pc.onnegotiationneeded = function() {
  56. util.log('`negotiationneeded` triggered');
  57. self._makeOffer();
  58. };
  59. };
  60. DataConnection.prototype._setupDataChannel = function() {
  61. var self = this;
  62. if (this._originator) {
  63. util.log('Creating data channel');
  64. // FOR NOW: reliable DC is not supported.
  65. this._dc = this._pc.createDataChannel(this.peer, { reliable: false });
  66. // Experimental reliable wrapper.
  67. if (this._options.reliable) {
  68. this._reliable = new Reliable(this._dc, util.debug);
  69. }
  70. this._configureDataChannel();
  71. } else {
  72. util.log('Listening for data channel');
  73. this._pc.ondatachannel = function(evt) {
  74. util.log('Received data channel');
  75. self._dc = evt.channel;
  76. // Experimental reliable wrapper.
  77. if (self._options.reliable) {
  78. self._reliable = new Reliable(self._dc, util.debug);
  79. }
  80. self._configureDataChannel();
  81. };
  82. }
  83. };
  84. /** Starts a PeerConnection and sets up handlers. */
  85. DataConnection.prototype._startPeerConnection = function() {
  86. util.log('Creating RTCPeerConnection');
  87. this._pc = new RTCPeerConnection(this._options.config, { optional:[ { RtpDataChannels: true } ]});
  88. };
  89. /** Takes care of ice handlers. */
  90. DataConnection.prototype._setupIce = function() {
  91. util.log('Listening for ICE candidates');
  92. var self = this;
  93. this._pc.onicecandidate = function(evt) {
  94. if (evt.candidate) {
  95. util.log('Received ICE candidates');
  96. self._socket.send({
  97. type: 'CANDIDATE',
  98. payload: {
  99. candidate: evt.candidate
  100. },
  101. dst: self.peer
  102. });
  103. }
  104. };
  105. };
  106. DataConnection.prototype._configureDataChannel = function() {
  107. var self = this;
  108. if (util.browserisms !== 'Webkit') {
  109. this._dc.binaryType = 'arraybuffer';
  110. }
  111. this._dc.onopen = function() {
  112. util.log('Data channel connection success');
  113. self.open = true;
  114. self.emit('open');
  115. self._pc.onicecandidate = null;
  116. };
  117. if (this._reliable) {
  118. this._reliable.onmessage = function(msg) {
  119. self.emit('data', msg);
  120. };
  121. } else {
  122. this._dc.onmessage = function(e) {
  123. self._handleDataMessage(e);
  124. };
  125. }
  126. this._dc.onclose = function(e) {
  127. self.emit('close');
  128. };
  129. };
  130. DataConnection.prototype._makeOffer = function() {
  131. var self = this;
  132. this._pc.createOffer(function(offer) {
  133. util.log('Created offer');
  134. // Reliable hack.
  135. if (self._options.reliable) {
  136. offer.sdp = Reliable.higherBandwidthSDP(offer.sdp);
  137. }
  138. self._pc.setLocalDescription(offer, function() {
  139. util.log('Set localDescription to offer');
  140. self._socket.send({
  141. type: 'OFFER',
  142. payload: {
  143. sdp: offer,
  144. serialization: self.serialization,
  145. metadata: self.metadata,
  146. reliable: self._options.reliable
  147. },
  148. dst: self.peer
  149. });
  150. }, function(err) {
  151. self.emit('error', err);
  152. util.log('Failed to setLocalDescription, ', err);
  153. });
  154. });
  155. };
  156. /** Create an answer for PC. */
  157. DataConnection.prototype._makeAnswer = function() {
  158. var self = this;
  159. this._pc.createAnswer(function(answer) {
  160. util.log('Created answer');
  161. // Reliable hack.
  162. if (self._options.reliable) {
  163. answer.sdp = Reliable.higherBandwidthSDP(answer.sdp);
  164. }
  165. self._pc.setLocalDescription(answer, function() {
  166. util.log('Set localDescription to answer');
  167. self._socket.send({
  168. type: 'ANSWER',
  169. payload: {
  170. sdp: answer
  171. },
  172. dst: self.peer
  173. });
  174. }, function(err) {
  175. self.emit('error', err);
  176. util.log('Failed to setLocalDescription, ', err)
  177. });
  178. }, function(err) {
  179. self.emit('error', err);
  180. util.log('Failed to create answer, ', err)
  181. });
  182. };
  183. DataConnection.prototype._cleanup = function() {
  184. if (!!this._dc && this._dc.readyState != 'closed') {
  185. this._dc.close();
  186. this._dc = null;
  187. }
  188. if (!!this._pc && this._pc.readyState != 'closed') {
  189. this._pc.close();
  190. this._pc = null;
  191. }
  192. };
  193. // Handles a DataChannel message.
  194. DataConnection.prototype._handleDataMessage = function(e) {
  195. var self = this;
  196. var data = e.data;
  197. var datatype = data.constructor;
  198. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  199. if (datatype === Blob) {
  200. util.blobToArrayBuffer(data, function(ab) {
  201. data = util.unpack(ab);
  202. self.emit('data', data);
  203. });
  204. return;
  205. } else if (datatype === ArrayBuffer) {
  206. data = util.unpack(data);
  207. } else if (datatype === String) {
  208. var ab = util.binaryStringToArrayBuffer(data);
  209. data = util.unpack(ab);
  210. }
  211. } else if (this.serialization === 'json') {
  212. data = JSON.parse(data);
  213. }
  214. this.emit('data', data);
  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. if (this._reliable) {
  235. // Note: reliable sending will make it so that you cannot customize
  236. // serialization.
  237. this._reliable.send(data);
  238. return;
  239. }
  240. var self = this;
  241. if (this.serialization === 'none') {
  242. this._dc.send(data);
  243. } else if (this.serialization === 'json') {
  244. this._dc.send(JSON.stringify(data));
  245. } else {
  246. var utf8 = (this.serialization === 'binary-utf8');
  247. var blob = util.pack(data, utf8);
  248. // DataChannel currently only supports strings.
  249. if (util.browserisms === 'Webkit') {
  250. util.blobToBinaryString(blob, function(str){
  251. self._dc.send(str);
  252. });
  253. } else {
  254. this._dc.send(blob);
  255. }
  256. }
  257. };
  258. DataConnection.prototype.handleSDP = function(sdp, type) {
  259. if (util.browserisms != 'Firefox') {
  260. sdp = new RTCSessionDescription(sdp);
  261. }
  262. var self = this;
  263. this._pc.setRemoteDescription(sdp, function() {
  264. util.log('Set remoteDescription: ' + type);
  265. if (type === 'OFFER') {
  266. self._makeAnswer();
  267. }
  268. }, function(err) {
  269. self.emit('error', err);
  270. util.log('Failed to setRemoteDescription, ', err);
  271. });
  272. };
  273. DataConnection.prototype.handleCandidate = function(message) {
  274. var candidate = new RTCIceCandidate(message.candidate);
  275. this._pc.addIceCandidate(candidate);
  276. util.log('Added ice candidate');
  277. };
  278. DataConnection.prototype.handleLeave = function() {
  279. util.log('Peer ' + this.peer + ' disconnected');
  280. this.close();
  281. };