# [觀念篇]WebRTC APIs - RTCPeerConnection object (Event handlers / methods)

# 學習目標

  • 了解 RTCPeerConnection 中的Event handlers及methods

延續上一章節的實作,這裡會一一講解每個步驟

# RTCPeerConnection 介紹

# constructor

pc = new RTCPeerConnection([configuration]);

我們將P2P建立連線分為幾個大方向來一一理解:

  • build RTCPeerConnection instance ( 初始化 )

      function buildPeerConnection () {
        const pc = new RTCPeerConnection();
        pc.onicecandidate = (e) => { /** 略..*/ };
        pc.oniceconnectionstatechange = (e) => { /** 略..*/ };
        pc.ontrack = (e) => { /** 略..*/ };
    
        return pc
      }
    

    第一部也就是初始化 RTCPeerConnection object,這邊先不帶入細部參數設定, 如果有興趣可以看看:RTCConfiguration_dictionary

    這邊在一開始初始化時,先綁定了以下幾個事件:

    • Event handlers
      • onicecandidate
      • oniceconnectionstatechange
      • ontrack

    onicecandidate: 當查找到相對應的遠端端口時會做onicecandidate,進行網路資訊的共享。

    ontrack: 當完成連線後,透過該事件能夠在遠端傳輸多媒體檔案時觸發,並處理接收。

  • 加入多媒體數據( MediaStreams object )

      const localStream = await navigator.mediaDevices.getUserMedia({
        audio: true,
        video: true,
      });
      // ....略
    
      localStream.getTracks().forEach((track) => localPeer.addTrack(track, localStream));
      // ...略
    
      remotePeer.ontrack = gotRemoteStream
      function gotRemoteStream(e) {
        if (remoteVideo.srcObject !== e.streams[0]) {
          remoteVideo.srcObject = e.streams[0];
        }
      }
    
    • methods

      • addTrack:加入MediaStream object到RTCPeerconnection中。
    • Event handlers

      • ontrack

# 總結

統整一下上述用到的apis :

# Event handlers

  • onicecandidate
  • oniceconnectionstatechange
  • ontrack

# methods

  • addTrack
  • createOffer
  • createAnswer
  • setLocalDescription
  • setRemoteDescription