dataconnection.ts 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. Negotiator.cleanup(this);
  141. super.emit(ConnectionEventType.Close);
  142. }
  143. /** Allows user to send data. */
  144. send(data: any, chunked: boolean): void {
  145. if (!this.open) {
  146. super.emit(
  147. ConnectionEventType.Error,
  148. new Error(
  149. "Connection is not open. You should listen for the `open` event before sending messages."
  150. )
  151. );
  152. return;
  153. }
  154. if (this._reliable) {
  155. // Note: reliable shim sending will make it so that you cannot customize
  156. // serialization.
  157. this._reliable.send(data);
  158. return;
  159. }
  160. if (this.serialization === SerializationType.JSON) {
  161. this._bufferedSend(JSON.stringify(data));
  162. } else if (
  163. this.serialization === SerializationType.Binary ||
  164. this.serialization === SerializationType.BinaryUTF8
  165. ) {
  166. const blob = util.pack(data);
  167. // For Chrome-Firefox interoperability, we need to make Firefox "chunk"
  168. // the data it sends out.
  169. const needsChunking =
  170. util.chunkedBrowsers[this._peerBrowser] ||
  171. util.chunkedBrowsers[util.browser];
  172. if (needsChunking && !chunked && blob.size > util.chunkedMTU) {
  173. this._sendChunks(blob);
  174. return;
  175. }
  176. // DataChannel currently only supports strings.
  177. if (!util.supports.sctp) {
  178. util.blobToBinaryString(blob, (str) => {
  179. this._bufferedSend(str);
  180. });
  181. } else if (!util.supports.binaryBlob) {
  182. // We only do this if we really need to (e.g. blobs are not supported),
  183. // because this conversion is costly.
  184. util.blobToArrayBuffer(blob, (ab) => {
  185. this._bufferedSend(ab);
  186. });
  187. } else {
  188. this._bufferedSend(blob);
  189. }
  190. } else {
  191. this._bufferedSend(data);
  192. }
  193. }
  194. private _bufferedSend(msg): void {
  195. if (this._buffering || !this._trySend(msg)) {
  196. this._buffer.push(msg);
  197. this._bufferSize = this._buffer.length;
  198. }
  199. }
  200. // Returns true if the send succeeds.
  201. private _trySend(msg): boolean {
  202. try {
  203. this.dataChannel.send(msg);
  204. } catch (e) {
  205. this._buffering = true;
  206. setTimeout(() => {
  207. // Try again.
  208. this._buffering = false;
  209. this._tryBuffer();
  210. }, 100);
  211. return false;
  212. }
  213. return true;
  214. }
  215. // Try to send the first message in the buffer.
  216. private _tryBuffer(): void {
  217. if (this._buffer.length === 0) {
  218. return;
  219. }
  220. const msg = this._buffer[0];
  221. if (this._trySend(msg)) {
  222. this._buffer.shift();
  223. this._bufferSize = this._buffer.length;
  224. this._tryBuffer();
  225. }
  226. }
  227. private _sendChunks(blob): void {
  228. const blobs = util.chunk(blob);
  229. for (let blob of blobs) {
  230. this.send(blob, true);
  231. }
  232. }
  233. handleMessage(message: ServerMessage): void {
  234. const payload = message.payload;
  235. switch (message.type) {
  236. case ServerMessageType.Answer:
  237. this._peerBrowser = payload.browser;
  238. // Forward to negotiator
  239. Negotiator.handleSDP(message.type, this, payload.sdp);
  240. break;
  241. case ServerMessageType.Candidate:
  242. Negotiator.handleCandidate(this, payload.candidate);
  243. break;
  244. default:
  245. util.warn(
  246. "Unrecognized message type:",
  247. message.type,
  248. "from peer:",
  249. this.peer
  250. );
  251. break;
  252. }
  253. }
  254. }