Saturday, January 23, 2021

WebRTC localConnection.setRemoteDescription(answer) pending for too long.

I am trying to implement a simple messaging mechanism between my browser (peer 1) and another browser (peer 2) on a different network. I am using Google's public STUN servers for learning.

Peer 1 does the following first:

const iceConfiguration = { iceServers: [ { urls: [ 'stun:stun1.1.google.com:19302', 'stun:stun2.1.google.com:19302', ], }, ] } const lc = new RTCPeerConnection(iceConfiguration) const dc = lc.createDataChannel("channel"); dc.onmessage = e => console.log("Just got a message: " + e.data); dc.onopen = e => console.log("Connection opened.") lc.onicecandidate = e => console.log("New Ice Candidate! Reprinting SDP" + JSON.stringify(lc.localDescription)) lc.createOffer().then(o => lc.setLocalDescription(o)).then(a => console.log("Set successfully.")) 

Then, I copy the generated SDP and send it to peer 2 which then does the following:

/* REMOTE_OFFER_OBJECT is the SDP generated by peer 1 */ const offer = REMOTE_OFFER_OBJECT const iceConfiguration = { iceServers: [ { urls: [ 'stun:stun1.1.google.com:19302', 'stun:stun2.1.google.com:19302', ], }, ] } const rc = new RTCPeerConnection(iceConfiguration); rc.onicecandidate = e => console.log("New Ice Candidate! Reprinting SDP" + JSON.stringify(rc.localDescription)) rc.ondatachannel = e => { rc.dc = e.channel; rc.dc.onmessage = e => console.log("New message: ", e.data) rc.dc.onopen = e => console.log("Connection opened.") } rc.setRemoteDescription(offer).then(a => console.log("Offer set.")) rc.createAnswer().then(a => rc.setLocalDescription(a)).then(a => console.log("Answer created.")) 

Peer 2 copies its generated SDP and sends it to peer 1 which then attempts to set its remote description:

const answer = REMOTE_ANSWER_OBJECT lc.setRemoteDescription(answer) 

The last statement keeps pending for too long and doesn't stop. It works properly if peer 2 is on my same network. I might be setting the STUN servers wrong or maybe the public Google STUN servers are a bad idea. Also, the createOffer() and createAnswer() calls generate several SDPs but I only copy and send the last ones. How can I properly set up the peer 2 peer connection with somebody on a different network in WebRTC? I hope there is a solution with free STUN servers as I am doing it for learning only at the moment.



No comments:

Post a Comment