DataConnection.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. import { util } from "../util";
  2. import logger from "../logger";
  3. import { Negotiator } from "../negotiator";
  4. import { ConnectionType, ServerMessageType } from "../enums";
  5. import { Peer } from "../peer";
  6. import { BaseConnection } from "../baseconnection";
  7. import { ServerMessage } from "../servermessage";
  8. import type { DataConnection as IDataConnection } from "./DataConnection";
  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 ||
  39. DataConnection.ID_PREFIX + util.randomToken();
  40. this.label = this.options.label || this.connectionId;
  41. this.reliable = !!this.options.reliable;
  42. this._negotiator = new Negotiator(this);
  43. this._negotiator.startConnection(
  44. this.options._payload || {
  45. originator: true,
  46. reliable: this.reliable,
  47. },
  48. );
  49. }
  50. /** Called by the Negotiator when the DataChannel is ready. */
  51. override _initializeDataChannel(dc: RTCDataChannel): void {
  52. this.dataChannel = dc;
  53. this.dataChannel.onopen = () => {
  54. logger.log(`DC#${this.connectionId} dc connection success`);
  55. this._open = true;
  56. this.emit("open");
  57. };
  58. this.dataChannel.onmessage = (e) => {
  59. logger.log(`DC#${this.connectionId} dc onmessage:`, e.data);
  60. // this._handleDataMessage(e);
  61. };
  62. this.dataChannel.onclose = () => {
  63. logger.log(`DC#${this.connectionId} dc closed for:`, this.peer);
  64. this.close();
  65. };
  66. }
  67. /**
  68. * Exposed functionality for users.
  69. */
  70. /** Allows user to close connection. */
  71. close(options?: { flush?: boolean }): void {
  72. if (options?.flush) {
  73. this.send({
  74. __peerData: {
  75. type: "close",
  76. },
  77. });
  78. return;
  79. }
  80. if (this._negotiator) {
  81. this._negotiator.cleanup();
  82. this._negotiator = null;
  83. }
  84. if (this.provider) {
  85. this.provider._removeConnection(this);
  86. this.provider = null;
  87. }
  88. if (this.dataChannel) {
  89. this.dataChannel.onopen = null;
  90. this.dataChannel.onmessage = null;
  91. this.dataChannel.onclose = null;
  92. this.dataChannel = null;
  93. }
  94. if (!this.open) {
  95. return;
  96. }
  97. this._open = false;
  98. super.emit("close");
  99. }
  100. protected abstract _send(data: any, chunked: boolean): void;
  101. /** Allows user to send data. */
  102. public send(data: any, chunked = false) {
  103. if (!this.open) {
  104. super.emit(
  105. "error",
  106. new Error(
  107. "Connection is not open. You should listen for the `open` event before sending messages.",
  108. ),
  109. );
  110. return;
  111. }
  112. return this._send(data, chunked);
  113. }
  114. async handleMessage(message: ServerMessage) {
  115. const payload = message.payload;
  116. switch (message.type) {
  117. case ServerMessageType.Answer:
  118. await this._negotiator.handleSDP(message.type, payload.sdp);
  119. break;
  120. case ServerMessageType.Candidate:
  121. await this._negotiator.handleCandidate(payload.candidate);
  122. break;
  123. default:
  124. logger.warn(
  125. "Unrecognized message type:",
  126. message.type,
  127. "from peer:",
  128. this.peer,
  129. );
  130. break;
  131. }
  132. }
  133. }