Binance Web3 Connector JS
    Preparing search index...

    Class WebsocketStreamsBase

    Hierarchy

    • WebsocketStreamsBase
      • WebsocketStreamsBase
    Index
    configuration: ConfigurationWebsocketStreams
    connectionPool: WebsocketConnection[]
    connectionTimers: Map<WebSocket, Set<TimerRecord>>
    logger: Logger
    signedStreams?: boolean
    streamCallbackMap: Map<string, Set<(data: unknown) => void>>
    streamIdIsStrictlyNumber?: boolean
    urlPaths: string[]
    wsURL: string
    • Cleans up WebSocket connection resources. Removes all listeners and clears any associated timers for the provided WebSocket client.

      Parameters

      • ws: WebSocket

        The WebSocket client to clean up.

      Returns void

      void

    • Clears all timers associated with a WebSocket connection.

      Parameters

      • connection: WebSocket

        The WebSocket client instance to clear timers for.

      Returns void

      void

    • Connects to the WebSocket Streams endpoint.

      • Managed-token mode (apiKey supplied): fetches a fresh auth token from the REST API, stores it, and schedules a 6-day renewal timer. The token is appended to the WebSocket URL on every connection
      • Bring-your-own-token mode (wsToken supplied): uses the provided token directly. No REST call is made and no renewal timer is started.

      Parameters

      • Optionalstream: string | string[]

        Stream name(s) to subscribe immediately after connect.

      Returns Promise<void>

      A promise that resolves when the connection is established.

    • Connects all WebSocket connections in the pool

      Parameters

      • url: string

        The Websocket server URL.

      • Optionalconnections: WebsocketConnection[]

        An optional array of WebSocket connections to connect. If not provided, all connections in the pool are connected.

      Returns Promise<void>

      A promise that resolves when all connections are established.

    • Creates a new WebSocket client instance.

      Parameters

      • url: string

        The URL to connect to.

      Returns WebSocket

      A new WebSocket client instance.

    • Disconnects from the WebSocket Streams endpoint and clears the token renewal timer (no-op in bring-your-own-token mode since no timer is started there).

      Returns Promise<void>

      A promise that resolves when the disconnection is complete.

    • Parameters

      • event: "open" | "message" | "error" | "close" | "ping" | "pong"
      • ...args: any[]

      Returns void

    • Enqueues a reconnection or renewal for a WebSocket connection. This method adds the connection, URL, and renewal flag to the connection queue, and then calls the processQueue method to initiate the reconnection or renewal process.

      Parameters

      • connection: WebsocketConnection

        The WebSocket connection to reconnect or renew.

      • url: string

        The URL to use for the reconnection or renewal.

      • isRenewal: boolean

        A flag indicating whether this is a renewal (true) or a reconnection (false).

      Returns void

    • Retrieves available WebSocket connections based on the connection mode and readiness. In 'single' mode, returns the first connection in the pool. In 'pool' mode, filters and returns connections that are ready for use.

      Parameters

      • OptionalallowNonEstablishedWebsockets: boolean

        Optional flag to include non-established WebSocket connections.

      • OptionalurlPath: string

        Optional URL path to filter connections.

      Returns WebsocketConnection[]

      An array of available WebSocket connections.

    • Gets a WebSocket connection from the pool or single connection. If the connection mode is 'single', it returns the first connection in the pool. If the connection mode is 'pool', it returns an available connection from the pool, using a round-robin selection strategy. If no available connections are found, it throws an error.

      Parameters

      • OptionalallowNonEstablishedWebsockets: boolean

        A boolean indicating whether to allow connections that are not established.

      • OptionalurlPath: string

        An optional URL path to filter connections.

      Returns WebsocketConnection

      The selected WebSocket connection.

    • Returns the additional handshake headers. For signed streams the X-MBX-APIKEY header is added.

      Returns Record<string, string>

      A record of header names and values.

    • Formats the WebSocket URL with stream and configuration parameters to be used for reconnection.

      Parameters

      • url: string

        The base WebSocket URL.

      • targetConnection: WebsocketConnection

        The target WebSocket connection.

      Returns string

      The formatted WebSocket URL with streams and optional parameters.

    • Overrides the base class's initConnect method to append the current auth token to the WebSocket URL as a query parameter. This is called both on the initial connection and on every server-driven 23-hour renewal — in both cases the token already in memory is reused (no extra fetch).

      Parameters

      • url: string

        The WebSocket URL to connect to.

      • isRenewal: boolean = false

        Whether this is a connection renewal.

      • Optionalconnection: WebsocketConnection

        Optional existing connection to reuse.

      Returns WebsocketConnection | undefined

      A WebsocketConnection instance, or undefined.

    • Checks if the WebSocket connection is currently open.

      Parameters

      • Optionalconnection: WebsocketConnection

        An optional WebSocket connection to check. If not provided, the entire connection pool is checked.

      Returns boolean

      true if the connection is open, false otherwise.

    • Checks if the provided WebSocket connection is ready for use. A connection is considered ready if it is open, has no pending reconnection, and has not been closed.

      Parameters

      • connection: WebsocketConnection

        The WebSocket connection to check.

      • OptionalallowNonEstablishedWebsockets: boolean

        An optional flag to allow non-established WebSocket connections.

      Returns boolean

      true if the connection is ready, false otherwise.

    • Checks if the message is serverShutdown. This is used to identify server shutdown events in incoming WebSocket messages.

      Parameters

      • message: any

        The message to check for a server shutdown event.

      Returns boolean

      true if the message indicates a server shutdown event, false otherwise.

    • Checks if the specified stream is currently subscribed.

      Parameters

      • stream: string

        The name of the stream to check.

      Returns boolean

      true if the stream is currently subscribed, false otherwise.

    • Parameters

      • event: "open" | "message" | "error" | "close" | "ping" | "pong"
      • listener: (...args: any[]) => void

      Returns void

    • Parameters

      • event: "open" | "message" | "error" | "close" | "ping" | "pong"
      • listener: (...args: any[]) => void

      Returns void

    • Handles incoming WebSocket messages, parsing the data and invoking the appropriate callback function. If the message contains a stream name that is registered in the streamCallbackMap, the corresponding callback function is called with the message data. If the message cannot be parsed, an error is logged.

      Parameters

      • data: string

        The raw WebSocket message data.

      • connection: WebsocketConnection

        The WebSocket connection that received the message.

      Returns void

    • Called when the WebSocket connection is opened. Processes any pending subscriptions for the target connection.

      Parameters

      • url: string

        The URL of the WebSocket connection.

      • targetConnection: WebsocketConnection

        The WebSocket connection that was opened.

      • oldWSConnection: WebSocket

      Returns void

    • Sends a ping message to all connected Websocket servers in the pool. If no connections are ready, a warning is logged. For each active connection, the ping message is sent, and debug logs provide details.

      Returns void

      Error if a Websocket client is not set for a connection.

    • Schedules a timer for a WebSocket connection and tracks it

      Parameters

      • connection: WebSocket

        WebSocket client instance

      • callback: () => void

        Function to execute when timer triggers

      • delay: number

        Time in milliseconds before callback execution

      • Optionaltype: "timeout" | "interval"

        Timer type ('timeout' or 'interval')

      Returns Timeout

      Timer handle

    • Sends a payload through the WebSocket connection.

      Type Parameters

      • T = unknown

      Parameters

      • payload: string

        Message to send.

      • Optionalid: string

        Optional request identifier.

      • OptionalpromiseBased: boolean

        Whether to return a promise.

      • Optionaltimeout: number

        Timeout duration in milliseconds.

      • Optionalconnection: WebsocketConnection

        The WebSocket connection to use.

      Returns void | Promise<WebsocketApiResponse<T>>

      A promise if promiseBased is true, void otherwise.

      Error if not connected or WebSocket client is not set.

    • Generates a stream key by combining a stream name with an optional URL path.

      Parameters

      • stream: string

        The stream name to use as the key or suffix.

      • OptionalurlPath: string

        Optional URL path to prepend to the stream name.

      Returns string

      A stream key in the format urlPath::stream if urlPath is provided, otherwise just the stream name.

    • Subscribes to one or multiple WebSocket streams Handles both single and pool modes

      Parameters

      • stream: string | string[]

        Single stream name or array of stream names to subscribe to

      • Optionalid: string | number

        Optional subscription ID

      • OptionalurlPath: string

        Optional URL path for the streams

      Returns void

      void

    • Unsubscribes from one or multiple WebSocket streams Handles both single and pool modes

      Parameters

      • stream: string | string[]

        Single stream name or array of stream names to unsubscribe from

      • Optionalid: string | number

        Optional unsubscription ID

      • OptionalurlPath: string

        Optional URL path for the streams

      Returns void

      void