dataconnection.ts 8.1 KB

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