dataconnection.ts 8.4 KB

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