'ondatachannel event never fires - WebRTC

Offer Side

let pc = new RTCPeerConnection({...});
let dc = pc.createDataChannel("msg");
dc.onopen = function (e) {
  console.log("Channel Opened", e);
};
dc.onclose = function (e) {
  console.log("Channel closed");
};

let offer = await pc.createOffer();
await pc.setLocalDescription(offer);

socket.emit("offer", JSON.stringify(pc.localDescription));

socket.on("answer", function (sdp) {
  pc.setRemoteDescription(JSON.parse(sdp));
});

Answer Side

let pc = new RTCPeerConnection({...});
pc.ondatachannel = function (e) {
  console.log(e);
};
socket.on("offer", async function (sdp) {
  await pc.setRemoteDescription(JSON.parse(sdp));
  let ans = await pc.createAnswer();
  pc.setLocalDescription(ans);
  socket.emit("answer", JSON.stringify(ans));
});

Ideally ondatachannel event should be fired.

Can someone tell me that why this is not working?

Thanks in advance :)

Source code

https://github.com/ats1999/RTSP-webRTC/tree/main/webRTC/data-channel

Do npm i to install the server side dependencies.



Solution 1:[1]

You are never exchanging ICE candidates (i.e. the address and port to use) and that is necessary to establish a connection (which in turn is necessary to open a datachannel). You have a onicecandidate handler:

    pc.onicecandidate = function (e) {
      if (e.candidate)
        try {
          //   pc.addIceCandidate(e.candidate);
        } catch (e) {}
      log("onicecandidate");
    };

but the (commented out) attempt to add the candidate to the local connection is wrong. What you need to do is to signal it to the other side via something like

socket.emit("candidate", JSON.stringify(e.candidate));

and then add it in a handler for the candidate event along these lines:

    socket.on("candidate", async function (candidate) {
       await pc.addIceCandidate(JSON.parse(candidate));
    });

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Philipp Hancke