Skip to content

文件传输

使用 WetRTC DataChannel 实现 P2P 文件传输。

发送端

ts
import { WetRTC, type SignalChannel } from '@wetspace/wetrtc'

declare const signal: SignalChannel

const rtc = new WetRTC({
  signal,
  direction: 'sendonly',
  dataChannels: [
    { label: 'file', options: { ordered: false, maxRetransmits: 3 } },
  ],
})

await rtc.connect()

const input = document.querySelector<HTMLInputElement>('input[type=file]')!
input.addEventListener('change', async () => {
  const file = input.files?.[0]
  if (!file) return

  console.log(`发送: ${file.name} (${(file.size / 1024 / 1024).toFixed(2)} MB)`)

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

  console.log('发送完成')
})

接收端

ts
import { WetRTC, type SignalChannel } from '@wetspace/wetrtc'

declare const signal: SignalChannel

const rtc = new WetRTC({
  signal,
  direction: 'recvonly',
})

rtc.data.onFile((meta, blob) => {
  console.log(`接收文件: ${meta.name} (${(meta.size / 1024 / 1024).toFixed(2)} MB)`)

  const url = URL.createObjectURL(blob)
  const a = document.createElement('a')
  a.href = url
  a.download = meta.name
  a.click()
  URL.revokeObjectURL(url)
})

await rtc.connect()

文本消息

除了文件传输,DataChannel 也支持文本消息:

ts
declare const rtc: import('@wetspace/wetrtc').WetRTC

const chat = rtc.data.getChannel('chat')
chat.send('Hello!')
chat.send(JSON.stringify({ type: 'ping', ts: Date.now() }))

rtc.on('message', (data, channel) => {
  console.log(`[${channel.label}]:`, data)
})

Released under the MIT License.