connection.js 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. /**
  2. * Wraps a DataChannel 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. 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. self._pc.setLocalDescription(offer, function() {
  135. util.log('Set localDescription to offer');
  136. self._socket.send({
  137. type: 'OFFER',
  138. payload: {
  139. sdp: offer,
  140. serialization: self.serialization,
  141. metadata: self.metadata,
  142. reliable: self._options.reliable
  143. },
  144. dst: self.peer
  145. });
  146. }, function(err) {
  147. self.emit('error', err);
  148. util.log('Failed to setLocalDescription, ', err);
  149. });
  150. });
  151. };
  152. /** Create an answer for PC. */
  153. DataConnection.prototype._makeAnswer = function() {
  154. var self = this;
  155. this._pc.createAnswer(function(answer) {
  156. util.log('Created answer');
  157. self._pc.setLocalDescription(answer, function() {
  158. util.log('Set localDescription to answer');
  159. self._socket.send({
  160. type: 'ANSWER',
  161. payload: {
  162. sdp: answer
  163. },
  164. dst: self.peer
  165. });
  166. }, function(err) {
  167. self.emit('error', err);
  168. util.log('Failed to setLocalDescription, ', err)
  169. });
  170. }, function(err) {
  171. self.emit('error', err);
  172. util.log('Failed to create answer, ', err)
  173. });
  174. };
  175. DataConnection.prototype._cleanup = function() {
  176. if (!!this._dc && this._dc.readyState != 'closed') {
  177. this._dc.close();
  178. this._dc = null;
  179. }
  180. if (!!this._pc && this._pc.readyState != 'closed') {
  181. this._pc.close();
  182. this._pc = null;
  183. }
  184. };
  185. // Handles a DataChannel message.
  186. DataConnection.prototype._handleDataMessage = function(e) {
  187. var self = this;
  188. var data = e.data;
  189. var datatype = data.constructor;
  190. if (this.serialization === 'binary' || this.serialization === 'binary-utf8') {
  191. if (datatype === Blob) {
  192. util.blobToArrayBuffer(data, function(ab) {
  193. data = util.unpack(ab);
  194. self.emit('data', data);
  195. });
  196. return;
  197. } else if (datatype === ArrayBuffer) {
  198. data = util.unpack(data);
  199. } else if (datatype === String) {
  200. var ab = util.binaryStringToArrayBuffer(data);
  201. data = util.unpack(ab);
  202. }
  203. } else if (this.serialization === 'json') {
  204. data = JSON.parse(data);
  205. }
  206. this.emit('data', data);
  207. };
  208. /**
  209. * Exposed functionality for users.
  210. */
  211. /** Allows user to close connection. */
  212. DataConnection.prototype.close = function() {
  213. this._cleanup();
  214. var self = this;
  215. if (this.open) {
  216. this._socket.send({
  217. type: 'LEAVE',
  218. dst: self.peer
  219. });
  220. }
  221. this.open = false;
  222. this.emit('close', this.peer);
  223. };
  224. /** Allows user to send data. */
  225. DataConnection.prototype.send = function(data) {
  226. if (this._reliable) {
  227. // Note: reliable sending will make it so that you cannot customize
  228. // serialization.
  229. this._reliable.send(data);
  230. return;
  231. }
  232. var self = this;
  233. if (this.serialization === 'none') {
  234. this._dc.send(data);
  235. } else if (this.serialization === 'json') {
  236. this._dc.send(JSON.stringify(data));
  237. } else {
  238. var utf8 = (this.serialization === 'binary-utf8');
  239. var blob = util.pack(data, utf8);
  240. // DataChannel currently only supports strings.
  241. if (util.browserisms === 'Webkit') {
  242. util.blobToBinaryString(blob, function(str){
  243. self._dc.send(str);
  244. });
  245. } else {
  246. this._dc.send(blob);
  247. }
  248. }
  249. };
  250. DataConnection.prototype.handleSDP = function(sdp, type) {
  251. if (util.browserisms != 'Firefox') {
  252. sdp = new RTCSessionDescription(sdp);
  253. }
  254. var self = this;
  255. this._pc.setRemoteDescription(sdp, function() {
  256. util.log('Set remoteDescription: ' + type);
  257. if (type === 'OFFER') {
  258. self._makeAnswer();
  259. }
  260. }, function(err) {
  261. self.emit('error', err);
  262. util.log('Failed to setRemoteDescription, ', err);
  263. });
  264. };
  265. DataConnection.prototype.handleCandidate = function(message) {
  266. var candidate = new RTCIceCandidate(message.candidate);
  267. this._pc.addIceCandidate(candidate);
  268. util.log('Added ice candidate');
  269. };
  270. DataConnection.prototype.handleLeave = function() {
  271. util.log('Peer ' + this.peer + ' disconnected');
  272. this.close();
  273. };