How to create data channel in WebRTC peer connection?

后端 未结 3 577
你的背包
你的背包 2021-01-31 06:24

I\'m trying to learn how to create an RTCPeerConnection so that I can use the DataChannel API. Here\'s what I have tried from what I understood:

<
3条回答
  •  孤城傲影
    2021-01-31 06:44

    Here is a sequence of events I have working today (Feb 2014) in Chrome. This is for a simplified case where peer 1 will stream video to peer 2.

    1. Set up some way for the peers to exchange messages. (The variance in how people accomplish this is what makes different WebRTC code samples so incommensurable, sadly. But mentally, and in your code organization, try to separate this logic out from the rest.)
    2. On each side, set up message handlers for the important signalling messages. You can set them up and leave them up. There are 3 core messages to handle & send:
      • an ice candidate sent from the other side ==> call addIceCandidate with it
      • an offer message ==> SetRemoteDescription with it, then make an answer & send it
      • an answer message ===> SetRemoteDescription with it
    3. On each side, create a new peerconnection object and attach event handlers to it for important events: onicecandidate, onremovestream, onaddstream, etc.
      • ice candidate ===> send it to other side
      • stream added ===> attach it to a video element so you can see it
    4. When both peers are present and all the handlers are in place, peer 1 gets a trigger message of some kind to start video capture (using the getUserMedia call)
    5. Once getUserMedia succeeds, we have a stream. Call addStream on the peer 1's peer connection object.
    6. Then -- and only then -- peer 1 makes an offer
    7. Due to the handlers we set up in step 2, peer 2 gets this and sends an answer
    8. Concurrently with this (and somewhat obscurely), the peer connection object starts producing ice candidates. They get sent back and forth between the two peers and handled (steps 2 & 3 above)
    9. Streaming starts by itself, opaquely, as a result of 2 conditions:
      • offer/answer exchange
      • ice candidates received, exchanged, and added

    I haven't found a way to add video after step 9. When I want to change something, I go back to step 3.

提交回复
热议问题