DataConnection.ts 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. import logger from "../logger";
  2. import { Negotiator } from "../negotiator";
  3. import {
  4. BaseConnectionErrorType,
  5. ConnectionType,
  6. DataConnectionErrorType,
  7. ServerMessageType,
  8. } from "../enums";
  9. import type { Peer } from "../peer";
  10. import { BaseConnection, type BaseConnectionEvents } from "../baseconnection";
  11. import type { ServerMessage } from "../servermessage";
  12. import type { EventsWithError } from "../peerError";
  13. import { randomToken } from "../utils/randomToken";
  14. export interface DataConnectionEvents
  15. extends EventsWithError<DataConnectionErrorType | BaseConnectionErrorType>,
  16. BaseConnectionEvents<DataConnectionErrorType | BaseConnectionErrorType> {
  17. /**
  18. * Emitted when data is received from the remote peer.
  19. */
  20. data: (data: unknown) => void;
  21. /**
  22. * Emitted when the connection is established and ready-to-use.
  23. */
  24. open: () => void;
  25. }
  26. /**
  27. * Wraps a DataChannel between two Peers.
  28. */
  29. export abstract class DataConnection extends BaseConnection<
  30. DataConnectionEvents,
  31. DataConnectionErrorType
  32. > {
  33. protected static readonly ID_PREFIX = "dc_";
  34. protected static readonly MAX_BUFFERED_AMOUNT = 8 * 1024 * 1024;
  35. private _negotiator: Negotiator<DataConnectionEvents, this>;
  36. abstract readonly serialization: string;
  37. readonly reliable: boolean;
  38. public get type() {
  39. return ConnectionType.Data;
  40. }
  41. constructor(peerId: string, provider: Peer, options: any) {
  42. super(peerId, provider, options);
  43. this.connectionId =
  44. this.options.connectionId || DataConnection.ID_PREFIX + randomToken();
  45. this.label = this.options.label || this.connectionId;
  46. this.reliable = !!this.options.reliable;
  47. this._negotiator = new Negotiator(this);
  48. this._negotiator.startConnection(
  49. this.options._payload || {
  50. originator: true,
  51. reliable: this.reliable,
  52. },
  53. );
  54. }
  55. /** Called by the Negotiator when the DataChannel is ready. */
  56. override _initializeDataChannel(dc: RTCDataChannel): void {
  57. this.dataChannel = dc;
  58. this.dataChannel.onopen = () => {
  59. logger.log(`DC#${this.connectionId} dc connection success`);
  60. this._open = true;
  61. this.emit("open");
  62. };
  63. this.dataChannel.onmessage = (e) => {
  64. logger.log(`DC#${this.connectionId} dc onmessage:`, e.data);
  65. // this._handleDataMessage(e);
  66. };
  67. this.dataChannel.onclose = () => {
  68. logger.log(`DC#${this.connectionId} dc closed for:`, this.peer);
  69. this.close();
  70. };
  71. }
  72. /**
  73. * Exposed functionality for users.
  74. */
  75. /** Allows user to close connection. */
  76. close(options?: { flush?: boolean }): void {
  77. if (options?.flush) {
  78. this.send({
  79. __peerData: {
  80. type: "close",
  81. },
  82. });
  83. return;
  84. }
  85. if (this._negotiator) {
  86. this._negotiator.cleanup();
  87. this._negotiator = null;
  88. }
  89. if (this.provider) {
  90. this.provider._removeConnection(this);
  91. this.provider = null;
  92. }
  93. if (this.dataChannel) {
  94. this.dataChannel.onopen = null;
  95. this.dataChannel.onmessage = null;
  96. this.dataChannel.onclose = null;
  97. this.dataChannel = null;
  98. }
  99. if (!this.open) {
  100. return;
  101. }
  102. this._open = false;
  103. super.emit("close");
  104. }
  105. protected abstract _send(data: any, chunked: boolean): void | Promise<void>;
  106. /** Allows user to send data. */
  107. public send(data: any, chunked = false) {
  108. if (!this.open) {
  109. this.emitError(
  110. DataConnectionErrorType.NotOpenYet,
  111. "Connection is not open. You should listen for the `open` event before sending messages.",
  112. );
  113. return;
  114. }
  115. return this._send(data, chunked);
  116. }
  117. async handleMessage(message: ServerMessage) {
  118. const payload = message.payload;
  119. switch (message.type) {
  120. case ServerMessageType.Answer:
  121. await this._negotiator.handleSDP(message.type, payload.sdp);
  122. break;
  123. case ServerMessageType.Candidate:
  124. await this._negotiator.handleCandidate(payload.candidate);
  125. break;
  126. default:
  127. logger.warn(
  128. "Unrecognized message type:",
  129. message.type,
  130. "from peer:",
  131. this.peer,
  132. );
  133. break;
  134. }
  135. }
  136. }