I've got a videoconference application that is working perfectly using HTML5 + WebRTC. The STUN/TURN server is provided by a third party company which is not for free. As you may know, WebRTC after some information exchange between browsers, it chooses the best way to connect both peers, and if possible it uses direct connection which doesn't involve the TURN server.
The question is, is it possible to detect when the RTCPeerConnection is stablished using direct connection or an intermidiate TURN server?
Peer connections is the part of the WebRTC specifications that deals with connecting two applications on different computers to communicate using a peer-to-peer protocol. The communication between peers can be video, audio or arbitrary binary data (for clients supporting the RTCDataChannel API).
You can easily determine if your server works with both tools or with your own JavaScript: A STUN server works if you can gather a candidate with type "srflx" . A TURN server works if you can gather a candidate with type "relay" .
For most WebRTC applications to function a server is required for relaying the traffic between peers, since a direct socket is often not possible between the clients (unless they reside on the same local network). The common way to solve this is by using a TURN server.
This snippet works in chrome
const stats = await pc.getStats()
let selectedLocalCandidate
for (const {type, state, localCandidateId} of stats.values())
if (type === 'candidate-pair' && state === 'succeeded' && localCandidateId) {
selectedLocalCandidate = localCandidateId
break
}
return !!selectedLocalCandidate && stats.get(selectedLocalCandidate)?.candidateType === 'relay')
The idea is to iterate each report in the stats (via pc.getStats()), looking for the selected ICE candidates pair, check for the id of the local candidate and determine whether the connection uses TURN by looking at the candidate's type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With