Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Peer

This is a wrapper for a RTCPeerConnection. It greatly simplifies the process of interacting with WebRTC, and adds some much-needed features.

The largest feature added in this wrapper is the ability to establish new Media channels without re-negotiating over a websocket connection. To accomplish this, the wrapper establishes an internal DataChannel to communicate.

The wrapper also creates a second, default DataChannel which can be automatically used for peer communications. Both of these channels are prearranged out-of-band, so they cost very little to create.

Hierarchy

Index

Constructors

constructor

Properties

Private Readonly awaitICE

awaitICE: Promise<null>

Private closed

closed: boolean = false

Private Readonly config

config: Partial<PeerConfig>

Private Readonly dataChannels

dataChannels: Record<string, RTCDataChannel>

Private Readonly dataSendQueue

dataSendQueue: Record<string, any[]>

Private hasConnected

hasConnected: boolean = false

Private initiator

initiator: boolean = false

Private Readonly pc

pc: RTCPeerConnection

Private Readonly pendingCandidates

pendingCandidates: any[] = []

Private Readonly timers

timers: any[] = []

Accessors

isClosed

  • get isClosed(): boolean
  • If this Peer connection has been terminated permanently.

    Returns boolean

isConnected

  • get isConnected(): boolean
  • If this Peer connection currently has an open connection.

    Returns boolean

isReady

  • get isReady(): boolean
  • If this Peer is currently connected, and has its internal channel open for communication.

    Returns boolean

isSignalStable

  • get isSignalStable(): boolean

localSdp

  • get localSdp(): null | string

remoteSdp

  • get remoteSdp(): null | string

Methods

addDataChannel

  • addDataChannel(channelName: string, opts?: RTCDataChannelInit): RTCDataChannel

addMedia

  • addMedia(media: MediaStream | MediaStreamTrack[], existingStream?: MediaStream): Promise<MediaStream>
  • Add a MediaStream or multiple MediaStreamTracks to this established connection.

    This requires renegotiation, which is handled internally through a hidden DataChannel. It does not require a middleman service.

    Resolves when the connection has stabilized after renegotiating the channels.

    see

    MediaStream

    see

    MediaStreamTrack

    Parameters

    • media: MediaStream | MediaStreamTrack[]

      Either an existing MediaStream, or an array of MediaStreamTracks.

    • Optional existingStream: MediaStream

      If media is an array of tracks, optionally pass an existing MediaStream to add these tracks into.

    Returns Promise<MediaStream>

    A MediaStream, which contains the given tracks.

close

  • close(intentional?: boolean): void
  • Permanently close this Peer, and kill any running background timers.

    Parameters

    • Default value intentional: boolean = true

    Returns void

emit

  • emit(event: "message" | "data" | "dataChannel" | "iceFinished" | "error" | "handshake" | "close" | "stream" | "ready" | "connect" | "iceEvent" | "disconnect", data?: any): void
  • Parameters

    • event: "message" | "data" | "dataChannel" | "iceFinished" | "error" | "handshake" | "close" | "stream" | "ready" | "connect" | "iceEvent" | "disconnect"
    • Optional data: any

    Returns void

Private emitReady

  • emitReady(): void
  • Emit a ready event, and an Open event if one hasn't already been sent.

    Returns void

Private fatalError

  • fatalError(err: Error): null
  • Emits a fatal Error, then terminates the Peer.

    Parameters

    • err: Error

    Returns null

handshake

  • handshake(data: any, initiate?: boolean): Promise<void>
  • This function handles all initial signaling steps, processing incoming data to establish a WebRTC Connection. Call this function with no params to start a connection as the initiator.

    Whenever this peer emits a handshake event, the data it produces should be relayed to the remote Peer. Whenever the remote Peer sends handshake data, the data should be passed into this local Peer via handshake(data).

    After an initial back-and-forth (unless Trickle ICE is enabled), no additional Handshake data should be required. Any subsequent negotiations will be handled internally via DataChannels.

    see

    https://webrtc.org/getting-started/peer-connections

    Parameters

    • data: any

      The data sent from the remote peer's handshake event, or none to initiate the handshake.

    • Default value initiate: boolean = true

      If we need to initiate the handshake.

    Returns Promise<void>

Private inBand

  • inBand(message: MessageEvent): Promise<void>
  • handle "in-band" negotiations via the internal metadata DataChannel.

    Parameters

    • message: MessageEvent

    Returns Promise<void>

makeAnswer

  • makeAnswer(incomingDescription: RTCSessionDescription): Promise<null | RTCSessionDescription>
  • Builds an answer in response to a connection request. The initiator peer just needs to setRemoteDescription this value, and the connection will be ready.

    Parameters

    • incomingDescription: RTCSessionDescription

    Returns Promise<null | RTCSessionDescription>

makeOffer

  • makeOffer(): Promise<RTCSessionDescription | null>
  • Builds a connection request. The non-initiator should call makeAnswer with this.

    Returns Promise<RTCSessionDescription | null>

Private makeTimer

  • makeTimer(timeout: number, cb: Function): clear
  • Build a timer that is managed by this Peer, and cancelled when the Peer closes.

    Parameters

    • timeout: number
    • cb: Function

    Returns clear

    A callback to clear the timeout.

on

  • on(event: "handshake", callback: (data: string) => void): () => void
  • on(event: "connect", callback: Function): () => void
  • on(event: "ready", callback: Function): () => void
  • on(event: "message", callback: (message: MessageEvent) => void): () => void
  • on(event: "data", callback: (data: string | ArrayBuffer | Blob | ArrayBufferView) => void): () => void
  • on(event: "dataChannel", callback: (peer: RTCDataChannel) => void): () => void
  • on(event: "stream", callback: (peer: MediaStream) => void): () => void
  • on(event: "error", callback: (err: Error) => void): () => void
  • on(event: "close", callback: Function): () => void
  • on(event: "disconnect", callback: Function): () => void
  • on(event: "iceFinished", callback: Function): () => void
  • on(event: "iceEvent", callback: (err: RTCPeerConnectionIceEvent) => void): () => void
  • Triggered when this Peer has created a handshake packet that must be sent to the remote Peer. If trickle ICE is enabled, this may also contain ICE candidates.

    Implementations should not worry about the content of this message, and should just relay it.

    The remote peer should receive this data, then call handshake(data) with it to continue the process.

    Call handshake() with no arguments to start this process on the initiator's side only.

    If you are using Switchboard, these handshake events will be handled automatically for you.

    Parameters

    • event: "handshake"
    • callback: (data: string) => void
        • (data: string): void
        • Parameters

          • data: string

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when this Peer has connected. This will only ever trigger once, on the initial connect.

    Parameters

    • event: "connect"
    • callback: Function

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when this Peer's connection has become stable. This will be triggered multiple times if new Media channels are added/removed.

    see

    addMedia

    Parameters

    • event: "ready"
    • callback: Function

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when this Peer's default DataChannel receives a MessageEvent.

    Parameters

    • event: "message"
    • callback: (message: MessageEvent) => void
        • (message: MessageEvent): void
        • Parameters

          • message: MessageEvent

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when this Peer's default DataChannel receives a MessageEvent.

    This is functionally the same as on('message'), and fires with it, except that it receives only the Event data. This callback has been implemented for better cross-compatibility.

    Parameters

    • event: "data"
    • callback: (data: string | ArrayBuffer | Blob | ArrayBufferView) => void
        • (data: string | ArrayBuffer | Blob | ArrayBufferView): void
        • Parameters

          • data: string | ArrayBuffer | Blob | ArrayBufferView

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when a new RTCDataChannel is created.

    Parameters

    • event: "dataChannel"
    • callback: (peer: RTCDataChannel) => void
        • (peer: RTCDataChannel): void
        • Parameters

          • peer: RTCDataChannel

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when a new MediaStream is created from the remote Peer.

    Parameters

    • event: "stream"
    • callback: (peer: MediaStream) => void
        • (peer: MediaStream): void
        • Parameters

          • peer: MediaStream

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when an Error is raised. This does not always mean the Peer must disconnect.

    Parameters

    • event: "error"
    • callback: (err: Error) => void

      A function that can receive the Error, if any, that caused termination.

        • (err: Error): void
        • Parameters

          • err: Error

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when this Peer has been closed, either locally or by the remote end. See the 'disconnect' event if you only wish to detect unexpected disconnections.

    Parameters

    • event: "close"
    • callback: Function

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when this Peer has been unexpectedly disconnected.

    Parameters

    • event: "disconnect"
    • callback: Function

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when all ICE discovery finishes (or the configured timer expires).

    see

    PeerConfig

    Parameters

    • event: "iceFinished"
    • callback: Function

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

  • Triggered when trickle ICE discovers another value, if trickle ICE is enabled.

    If enabled, the handshake event already handles emitting these in the format it expects.

    see

    PeerConfig

    Parameters

    • event: "iceEvent"
    • callback: (err: RTCPeerConnectionIceEvent) => void
        • (err: RTCPeerConnectionIceEvent): void
        • Parameters

          • err: RTCPeerConnectionIceEvent

          Returns void

    Returns () => void

    A function to call, in order to unsubscribe.

      • (): void
      • Returns void

Private onConnectionState

  • onConnectionState(ev: Event): void
  • Triggered when the connection state changes for the current connection. Handles emitting some events.

    Parameters

    • ev: Event

    Returns void

Private onTrack

  • onTrack(ev: RTCTrackEvent): void
  • Called when a new Media Stream/Track is added by the remote Peer.

    Parameters

    • ev: RTCTrackEvent

    Returns void

once

  • once(event: string, callback: Function): (Anonymous function)
  • Same as on(), but only triggers one time & automatically cleans up.

    see

    on for the available specific events.

    Parameters

    • event: string
    • callback: Function

    Returns (Anonymous function)

Private registerDataChannel

  • registerDataChannel(ch: RTCDataChannel): void
  • Internal. Registers event handlers for the channel, and adds it to the tracked list of channels.

    Parameters

    • ch: RTCDataChannel

    Returns void

removeAllListeners

  • removeAllListeners(event?: undefined | string): this
  • Removes all non-permanent callbacks for the given event type, or every event type if none is given.

    Parameters

    • Optional event: undefined | string

    Returns this

removeDataChannel

  • removeDataChannel(channelName: string): void
  • Remove the given data channel.

    Parameters

    • channelName: string

    Returns void

send

  • send(data: string | ArrayBuffer | Blob | ArrayBufferView, channelName?: string): void
  • Send data to the connected Peer.

    see

    addDataChannel

    Parameters

    • data: string | ArrayBuffer | Blob | ArrayBufferView

      The data to send.

    • Default value channelName: string = "default"

      The channel name to use. Defaults to the "default" DataChannel created on startup.

    Returns void

Private sendMeta

  • sendMeta(data: any): void
  • Internal send method, for ease of use.

    Parameters

    • data: any

    Returns void

Private waitForICE

  • waitForICE(): Promise<null | void>
  • Wait for trickle ICE to finish, up to a given timeout - starting after the first candidate is received. if trickleICE is set, this does not wait.

    Returns Promise<null | void>

Static Private formatSdp

  • formatSdp(sdp: string | undefined): null | string
  • Some browsers (Mozilla) mess with the SDP layout, for no real reason... This is an attempt to support all browser SDP formats by filtering to the specific bits we expect to be useful.

    Parameters

    • sdp: string | undefined

    Returns null | string

Generated using TypeDoc