DataConnection.ts 3.6 KB

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