dataconnection.ts 7.8 KB

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