Skip to content

DataManager

数据通道管理器,负责创建、管理 WebRTC DataChannel,提供消息收发和文件传输能力。通过 rtc.data 访问。

导入

ts
import { DataManager } from '@wetspace/wetrtc'

构造函数

ts
new DataManager(pc: RTCPeerConnection)

方法

configureChannels()

ts
configureChannels(configs: DataChannelConfig[]): void

批量配置预定义的 DataChannel。

initConfiguredChannels()

ts
initConfiguredChannels(): void

初始化预配置的 DataChannel(在 connect() 时自动调用)。

getChannel()

ts
getChannel(label: string): RTCDataChannel | undefined

按标签获取 DataChannel。

ts
const chat = rtc.data.getChannel('chat')
chat?.send('Hello!')

createChannel()

ts
createChannel(label: string, options?: DataChannelOptions): RTCDataChannel

动态创建 DataChannel。

ts
const channel = rtc.data.createChannel('custom', { ordered: false })

registerRemoteChannel()

ts
registerRemoteChannel(event: RTCDataChannelEvent): void

注册远端创建的 DataChannel(内部由 datachannel 事件自动调用)。

onMessage()

ts
onMessage(handler: (data: unknown, label?: string) => void): () => void

注册全局消息监听器,返回取消监听的函数。

sendFile()

ts
sendFile(file: File, options?: FileTransferOptions): Promise<void>

发送文件(分片传输)。

ts
await rtc.data.sendFile(file, {
  chunkSize: 16384,
  maxRetries: 3,
  maxFileSize: 1024 * 1024 * 1024,
  onProgress: (sent, total) => {
    console.log(`${((sent / total) * 100).toFixed(1)}%`)
  },
})

onFile()

ts
onFile(handler: (meta: FileMeta, blob: Blob) => void): () => void

注册文件接收监听器。文件会在接收完成并通过分片数/大小校验后回调。

dispose()

ts
dispose(): void

关闭所有 DataChannel 并释放资源。

类型

ts
interface DataChannelOptions {
  ordered?: boolean
  maxPacketLifeTime?: number
  maxRetransmits?: number
  protocol?: string
  negotiated?: boolean
  id?: number
}

interface DataChannelConfig {
  label: string
  options?: DataChannelOptions
}

interface FileTransferOptions {
  chunkSize?: number      // 默认 16384
  maxRetries?: number     // 默认 3
  onProgress?: (sent: number, total: number) => void
  maxFileSize?: number
  signal?: AbortSignal
  bufferThreshold?: number
  bufferTimeout?: number
}

interface FileMeta {
  name: string
  size: number
  type: string
}

Released under the MIT License.