dataconnection.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. import { util } from "./util";
  2. import Negotiator from "./negotiator";
  3. import { Reliable } from "reliable";
  4. import {
  5. ConnectionType,
  6. ConnectionEventType,
  7. SerializationType
  8. } from "./enums";
  9. import { Peer } from "./peer";
  10. import { BaseConnection } from "./baseconnection";
  11. import { ServerMessage } from "./servermessage";
  12. /**
  13. * Wraps a DataChannel between two Peers.
  14. */
  15. export class DataConnection extends BaseConnection {
  16. private static readonly ID_PREFIX = "dc_";
  17. readonly label: string;
  18. readonly serialization: SerializationType;
  19. readonly reliable: boolean;
  20. get type() {
  21. return ConnectionType.Data;
  22. }
  23. private _buffer: any[] = [];
  24. private _bufferSize = 0;
  25. private _buffering = false;
  26. private _chunkedData = {};
  27. private _peerBrowser: any;
  28. private _dc: RTCDataChannel;
  29. private _reliable: Reliable;
  30. get dataChannel() {
  31. return this._dc;
  32. }
  33. constructor(peerId: string, provider: Peer, options: any) {
  34. super(peerId, provider, options);
  35. this.connectionId =
  36. options.connectionId || DataConnection.ID_PREFIX + util.randomToken();
  37. this.label = options.label || this.connectionId;
  38. this.serialization = options.serialization;
  39. this.reliable = options.reliable;
  40. if (options._payload) {
  41. this._peerBrowser = options._payload.browser;
  42. }
  43. Negotiator.startConnection(
  44. this,
  45. options._payload || {
  46. originator: true
  47. }
  48. );
  49. }
  50. /** Called by the Negotiator when the DataChannel is ready. */
  51. initialize(dc: RTCDataChannel): void {
  52. this._dc = dc;
  53. this._configureDataChannel();
  54. }
  55. private _configureDataChannel(): void {
  56. if (util.supports.sctp) {
  57. this.dataChannel.binaryType = "arraybuffer";
  58. }
  59. const self = this;
  60. this.dataChannel.onopen = function() {
  61. util.log("Data channel connection success");
  62. self._open = true;
  63. self.emit(ConnectionEventType.Open);
  64. };
  65. // Use the Reliable shim for non Firefox browsers
  66. if (!util.supports.sctp && this.reliable) {
  67. this._reliable = new Reliable(this.dataChannel, util.debug);
  68. }
  69. if (this._reliable) {
  70. this._reliable.onmessage = function(msg) {
  71. self.emit(ConnectionEventType.Data, msg);
  72. };
  73. } else {
  74. this.dataChannel.onmessage = function(e) {
  75. self._handleDataMessage(e);
  76. };
  77. }
  78. this.dataChannel.onclose = function(e) {
  79. util.log("DataChannel closed for:", self.peer);
  80. self.close();
  81. };
  82. }
  83. // Handles a DataChannel message.
  84. private _handleDataMessage(e): void {
  85. let data = e.data;
  86. const datatype = data.constructor;
  87. if (
  88. this.serialization === SerializationType.Binary ||
  89. this.serialization === SerializationType.BinaryUTF8
  90. ) {
  91. if (datatype === Blob) {
  92. const self = this;
  93. // Datatype should never be blob
  94. util.blobToArrayBuffer(data, function(ab) {
  95. data = util.unpack(ab);
  96. self.emit(ConnectionEventType.Data, data);
  97. });
  98. return;
  99. } else if (datatype === ArrayBuffer) {
  100. data = util.unpack(data);
  101. } else if (datatype === String) {
  102. // String fallback for binary data for browsers that don't support binary yet
  103. const ab = util.binaryStringToArrayBuffer(data);
  104. data = util.unpack(ab);
  105. }
  106. } else if (this.serialization === SerializationType.JSON) {
  107. data = JSON.parse(data);
  108. }
  109. // Check if we've chunked--if so, piece things back together.
  110. // We're guaranteed that this isn't 0.
  111. if (data.__peerData) {
  112. const id = data.__peerData;
  113. const chunkInfo = this._chunkedData[id] || {
  114. data: [],
  115. count: 0,
  116. total: data.total
  117. };
  118. chunkInfo.data[data.n] = data.data;
  119. chunkInfo.count++;
  120. if (chunkInfo.total === chunkInfo.count) {
  121. // Clean up before making the recursive call to `_handleDataMessage`.
  122. delete this._chunkedData[id];
  123. // We've received all the chunks--time to construct the complete data.
  124. data = new Blob(chunkInfo.data);
  125. this._handleDataMessage({ data: data });
  126. }
  127. this._chunkedData[id] = chunkInfo;
  128. return;
  129. }
  130. super.emit(ConnectionEventType.Data, data);
  131. }
  132. /**
  133. * Exposed functionality for users.
  134. */
  135. /** Allows user to close connection. */
  136. close(): void {
  137. if (!this.open) {
  138. return;
  139. }
  140. this._open = false;
  141. Negotiator.cleanup(this);
  142. super.emit(ConnectionEventType.Close);
  143. }
  144. /** Allows user to send data. */
  145. send(data: any, chunked: boolean): void {
  146. if (!this.open) {
  147. super.emit(
  148. ConnectionEventType.Error,
  149. new Error(
  150. "Connection is not open. You should listen for the `open` event before sending messages."
  151. )
  152. );
  153. return;
  154. }
  155. if (this._reliable) {
  156. // Note: reliable shim sending will make it so that you cannot customize
  157. // serialization.
  158. this._reliable.send(data);
  159. return;
  160. }
  161. if (this.serialization === SerializationType.JSON) {
  162. this._bufferedSend(JSON.stringify(data));
  163. } else if (
  164. this.serialization === SerializationType.Binary ||
  165. this.serialization === SerializationType.BinaryUTF8
  166. ) {
  167. const blob = util.pack(data);
  168. // For Chrome-Firefox interoperability, we need to make Firefox "chunk"
  169. // the data it sends out.
  170. const needsChunking =
  171. util.chunkedBrowsers[this._peerBrowser] ||
  172. util.chunkedBrowsers[util.browser];
  173. if (needsChunking && !chunked && blob.size > util.chunkedMTU) {
  174. this._sendChunks(blob);
  175. return;
  176. }
  177. const self = this;
  178. // DataChannel currently only supports strings.
  179. if (!util.supports.sctp) {
  180. util.blobToBinaryString(blob, function(str) {
  181. self._bufferedSend(str);
  182. });
  183. } else if (!util.supports.binaryBlob) {
  184. // We only do this if we really need to (e.g. blobs are not supported),
  185. // because this conversion is costly.
  186. util.blobToArrayBuffer(blob, function(ab) {
  187. self._bufferedSend(ab);
  188. });
  189. } else {
  190. this._bufferedSend(blob);
  191. }
  192. } else {
  193. this._bufferedSend(data);
  194. }
  195. }
  196. private _bufferedSend(msg): void {
  197. if (this._buffering || !this._trySend(msg)) {
  198. this._buffer.push(msg);
  199. this._bufferSize = this._buffer.length;
  200. }
  201. }
  202. // Returns true if the send succeeds.
  203. private _trySend(msg): boolean {
  204. try {
  205. this.dataChannel.send(msg);
  206. } catch (e) {
  207. this._buffering = true;
  208. const self = this;
  209. setTimeout(function() {
  210. // Try again.
  211. self._buffering = false;
  212. self._tryBuffer();
  213. }, 100);
  214. return false;
  215. }
  216. return true;
  217. }
  218. // Try to send the first message in the buffer.
  219. private _tryBuffer(): void {
  220. if (this._buffer.length === 0) {
  221. return;
  222. }
  223. const msg = this._buffer[0];
  224. if (this._trySend(msg)) {
  225. this._buffer.shift();
  226. this._bufferSize = this._buffer.length;
  227. this._tryBuffer();
  228. }
  229. }
  230. private _sendChunks(blob): void {
  231. const blobs = util.chunk(blob);
  232. for (let blob of blobs) {
  233. this.send(blob, true);
  234. }
  235. }
  236. handleMessage(message: ServerMessage): void {
  237. const payload = message.payload;
  238. switch (message.type) {
  239. case "ANSWER":
  240. this._peerBrowser = payload.browser;
  241. // Forward to negotiator
  242. Negotiator.handleSDP(message.type, this, payload.sdp);
  243. break;
  244. case "CANDIDATE":
  245. Negotiator.handleCandidate(this, payload.candidate);
  246. break;
  247. default:
  248. util.warn(
  249. "Unrecognized message type:",
  250. message.type,
  251. "from peer:",
  252. this.peer
  253. );
  254. break;
  255. }
  256. }
  257. }