用 Peer.js 愉快上手 P2P 通信

前言

哈嘍,大家好,我是海怪。

最近公司項(xiàng)目需要用到視頻流的技術(shù),所以就研究了一下 WebRTC,正好看到 Peer.js 這個(gè)框架,用它做了一個(gè)小 Demo,今天就跟大家做個(gè)簡(jiǎn)單的分享吧。

WebRTC 是什么

WebRTC(Web Real Time Communication)也叫做 網(wǎng)絡(luò)實(shí)時(shí)通信,它可以 允許網(wǎng)頁應(yīng)用不通過中間服務(wù)器就能互相直接傳輸任意數(shù)據(jù),比如視頻流、音頻流、文件流、普通數(shù)據(jù)等。 它逐漸也成為了瀏覽器的一套規(guī)范,提供了如下能力:

  • 捕獲視頻和音頻流
  • 進(jìn)行音頻和視頻通信
  • 進(jìn)行任意數(shù)據(jù)的通信

這 3 個(gè)功能分別對(duì)應(yīng)了 3 個(gè) API:

  • MediaStream (又稱getUserMedia)
  • RTCPeerConnection
  • RTCDataChannel

雖然這些 API 看起來很簡(jiǎn)單,但是使用起來非常復(fù)雜。不僅要了解 "candidate", "ICE" 這些概念,還要寫很多回調(diào)才能實(shí)現(xiàn)端對(duì)端通信。而且由于不同瀏覽器對(duì) WebRTC 的支持不盡相同,所以還需要引入 Adapter.js 來做兼容。光看下面這個(gè)連接步驟圖就頭疼:

原生 WebRTC 連接步驟

所以,為了更簡(jiǎn)單地使用 WebRTC 來做端對(duì)端傳輸,Peer.js 做了底層的 API 調(diào)用以及兼容,簡(jiǎn)化了整個(gè)端對(duì)端實(shí)現(xiàn)過程。

下面就用它來實(shí)現(xiàn)一個(gè)視頻聊天室吧。

文章代碼都放在 Github 項(xiàng)目 上了,你也可以點(diǎn)擊 預(yù)覽鏈接 來查看。

視頻效果

項(xiàng)目初始化

首先使用 create-react-app 來創(chuàng)建一個(gè) React 項(xiàng)目:

create-react-app react-chatroom

將一些無用的文件清理掉,只留下一個(gè) App.js 即可。為了界面更好看,這里可以使用 antd 作為 UI 庫:

npm i antd

最后在 index.js 中引入 CSS:

import 'antd/dist/antd.css'

布局

安裝 peer.js

npm i peerjs

寫好整個(gè)頁面的布局:

const App = () => {
  const [loading, setLoading] = useState(true);

  const [localId, setLocalId] = useState('');
  const [remoteId, setRemoteId] = useState('');

  const [messages, setMessages] = useState([]);
  const [customMsg, setCustomMsg] = useState('');

  const currentCall = useRef();
  const currentConnection = useRef();

  const peer = useRef()

  const localVideo = useRef();
  const remoteVideo = useRef();

  useEffect(() => {
    createPeer()

    return () => {
      endCall()
    }
  }, [])

  // 結(jié)束通話
  const endCall = () => {}

  // 創(chuàng)建本地 Peer
  const createPeer = () => {}

  // 開始通話
  const callUser = async () => {}

  // 發(fā)送文本
  const sendMsg = () => {}

  return (
    <div className={styles.container}>
      <h1>本地 Peer ID: {localId || <Spin spinning={loading} />}</h1>

      <div>
        <Space>
          <Input value={remoteId} onChange={e => setRemoteId(e.target.value)} type="text" placeholder="對(duì)方 Peer 的 Id"/>
          <Button type="primary" onClick={callUser}>視頻通話</Button>
          <Button type="primary" danger onClick={endCall}>結(jié)束通話</Button>
        </Space>
      </div>

      <Row gutter={16} className={styles.live}>
        <Col span={12}>
          <h2>本地?cái)z像頭</h2>
          <video controls autoPlay ref={localVideo} muted />
        </Col>
        <Col span={12}>
          <h2>遠(yuǎn)程攝像頭</h2>
          <video controls autoPlay ref={remoteVideo} />
        </Col>
      </Row>

      <h1>發(fā)送消息</h1>
      <div>
        <h2>消息列表</h2>
        <List
          itemLayout="horizontal"
          dataSource={messages}
          renderItem={msg => (
            <List.Item key={msg.id}>
              <div>
                <span>{msg.type === 'local' ? <Tag color="red">我</Tag> : <Tag color="green">對(duì)方</Tag>}</span>
                <span>{msg.data}</span>
              </div>
            </List.Item>
          )}
        />

        <h2>自定義消息</h2>
        <TextArea
          placeholder="發(fā)送自定義內(nèi)容"
          value={customMsg}
          onChange={e => setCustomMsg(e.target.value)}
          onEnter={sendMsg}
          rows={4}
        />
        <Button
          disabled={!customMsg}
          type="primary"
          onClick={sendMsg}
          style={{ marginTop: 16 }}>
          發(fā)送
        </Button>
      </div>
    </div>
  );
}

效果如下:

布局

創(chuàng)建本地 Peer

由于我們要對(duì)接外部別人的 Peer,所以在加載這個(gè)頁面時(shí)就要?jiǎng)?chuàng)建一個(gè) Peer,在剛剛的 createPeer 中寫入:

const createPeer = () => {
  peer.current = new Peer();
  peer.current.on("open", (id) => {
    setLocalId(id)
    setLoading(false)
  });

  // 純數(shù)據(jù)傳輸
  peer.current.on('connection', (connection) => {
    // 接受對(duì)方傳來的數(shù)據(jù)
    connection.on('data', (data) => {
      setMessages((curtMessages) => [
        ...curtMessages,
        { id: curtMessages.length + 1, type: 'remote', data }
      ])
    })

    // 記錄當(dāng)前的 connection
    currentConnection.current = connection
  })

  // 媒體傳輸
  peer.current.on('call', async (call) => {
    if (window.confirm(`是否接受 ${call.peer}?`)) {
      // 獲取本地流
      const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
      localVideo.current.srcObject = stream
      localVideo.current.play()

      // 響應(yīng)
      call.answer(stream)

      // 監(jiān)聽視頻流,并更新到 remoteVideo 上
      call.on('stream', (stream) => {
        remoteVideo.current.srcObject = stream;
        remoteVideo.current.play()
      })

      currentCall.current = call
    } else {
      call.close()
    }
  })
}

上面主要做了這么幾件事:

  • new 了一個(gè) Peer 實(shí)例,并在這個(gè)實(shí)例上監(jiān)聽了很多事件
  • 監(jiān)聽 open 事件,打開通道后更新本地 localId
  • 監(jiān)聽 connect 事件,在連接成功后,將對(duì)方 Peer 的消息都更新到 messages 數(shù)組
  • 監(jiān)聽 call 事件,當(dāng)對(duì)方 Peer make call
    • getUserMedia 捕獲本地的音視頻流,并更新到 localVideo
    • 監(jiān)聽 stream 事件,將對(duì)方 Peer 的音視頻流更新到 remoteVideo

整個(gè)創(chuàng)建以及監(jiān)聽的過程就完成了。不過別忘了要在這個(gè)頁面關(guān)閉后結(jié)束整個(gè)鏈接:

useEffect(() => {
  createPeer()

  return () => {
    endCall()
  }
}, [])

const endCall = () => {
  if (currentCall.current) {
    currentCall.current.close()
  }
}

發(fā)送邀請(qǐng)

如果這個(gè)頁面要作為發(fā)送方,那么這個(gè) Peer 就需要完成 make a call 的任務(wù),在 callUser 寫入:

const callUser = async () => {
  // 獲取本地視頻流
  const stream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true })
  localVideo.current.srcObject = stream
  localVideo.current.play()

  // 數(shù)據(jù)傳輸
  const connection = peer.current.connect(remoteId);
  currentConnection.current = connection
  connection.on('open', () => {
    message.info('已連接')
  })

  // 多媒體傳輸
  const call = peer.current.call(remoteId, stream)
  call.on("stream", (stream) => {
    remoteVideo.current.srcObject = stream;
    remoteVideo.current.play()
  });
  call.on("error", (err) => {
    console.error(err);
  });
  call.on('close', () => {
    endCall()
  })

  currentCall.current = call
}

這里主要做了如下事件:

  • 捕獲本地音視頻流,并更新到 localVideo
  • 通過 remote peer id 連接對(duì)方 Peer
  • 通過 remote peer id 給對(duì)方 make a call,并監(jiān)聽這個(gè) call 的內(nèi)容
    • 監(jiān)聽 stream 事件,將對(duì)方發(fā)送的流更新到 remoteVideo
    • 監(jiān)聽 error 事件,上報(bào)qyak
    • 監(jiān)聽 close 事件,隨時(shí)關(guān)閉

總體來說和上面的 創(chuàng)建 Peer 的流程是差不多的,唯一的區(qū)別就是之前是 new Peer()answer,這里是 connectcall

發(fā)送文本

除了音視頻流的互傳,還可以傳輸普通文本,這里我們?cè)偻晟埔幌?sendMsg

const sendMsg = () => {
  // 發(fā)送自定義內(nèi)容
  if (!currentConnection.current) {
    message.warn('還未建立鏈接')
  }
  if (!customMsg) {
    return;
  }
  currentConnection.current.send(customMsg)
  setMessages((curtMessages) => [
    ...curtMessages,
    { id: curtMessages.length + 1, type: 'local', data: customMsg }
  ])
  setCustomMsg('');
}

這里直接調(diào)用當(dāng)前的 connectionsend() 就可以了。

效果

第一步,打開兩個(gè)頁面 A 和 B。

image

第二步,將 B 頁面(接收方)的 peer id 填在 A 頁面(發(fā)起方)的輸入框內(nèi),點(diǎn)擊【視頻通話】。

image

第三步,在 B 頁面(接收方)點(diǎn)擊 confirm 的【確認(rèn)】:

image

然后就可以完成視頻通話啦:

視頻效果

總結(jié)

總的來說,使用 Peer.js 來做端對(duì)端的信息互傳還是比較方便的。

P2P 一大特點(diǎn)就是可以不需要中間服務(wù)器就能完成兩點(diǎn)之間的數(shù)據(jù)傳輸。不過也并不是所有情況都能 “完全脫離服務(wù)器”,在某些情況下,比如防火墻阻隔的通信,還是需要一個(gè)中介服務(wù)器來關(guān)聯(lián)兩端,然后再開始端對(duì)端的通信。而 Peer.js 自己就實(shí)現(xiàn)了一個(gè)免費(fèi)的中介服務(wù)器,默認(rèn)下是連接到它的中介服務(wù)器上(數(shù)據(jù)傳輸不走這個(gè) Server),當(dāng)然你也可以使用它的 PeerServer 來創(chuàng)建自己的服務(wù)器。

const { PeerServer } = require('peer');

const peerServer = PeerServer({ port: 9000, path: '/myapp' });
<script>
    const peer = new Peer('someid', {
      host: 'localhost',
      port: 9000,
      path: '/myapp'
    });
</script>

WebRTC API 在安全性方面也有很多限制:

image

總之,端對(duì)端技術(shù)在某些要求實(shí)時(shí)性很強(qiáng)的場(chǎng)景下是很有用的。使用 Peer.js 可以很方便地實(shí)現(xiàn)端對(duì)端互傳。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容