iosswiftwebrtcrtcdatachannel

Why I have to open data channel before send peer connection offer?


I'm coding a simple chat application and I'd like to add a shared drawing canvas to my application which is using data channel to send canvas points between them. But it's a optional specification so I don't want open a data channel each time of opening a chat. If I open data channel after establish the peer connection (after offer), I can not send any data over data channel. Otherwise I can send (I got this point from here: https://stackoverflow.com/a/35141500/5663292). So why I have to open data channel before peer connection offer?


Solution

  • The SDP offer/answer is what establishes how exactly your peers want to communicate. The offer includes the actual connection method (IP/port/TURN relay) and what streams, codecs and channels you want to use. The answer narrows this down/confirms what the other peer can accept.

    If you want to add anything to the communication, like an additional media stream or a data channel, you need to inform the other peer of that, otherwise it doesn't expect anything/can't handle it.

    The flow is always:

    1. prepare anything you want to send to a remote peer on your local RTCPeerConnection
    2. generate a local description
    3. send it to the remote peer
    4. await the remote peer's answer
    5. incorporate the remote's answer (setRemoteDescription)

    Only then are both peers on the same page and can really talk to one another. Repeat this procedure whenever necessary, i.e. whenever you substantially change anything about what you're sending.