I'm having trouble understanding webRTC with it's PeerConnection and 'onicecandidate' event.
As far as I understand it you must initiate a peerconnection using a STUN (or TURN) server, because it will send you back your ICE candidate for communication with another peer.
I've seen examples leaving the server parameter of the PeerConnection object out, which I don't understand as well, but let's just say it does need the server parameter.
So, when I write down the following code:
var pc, ice = { "iceServers": [{ "url": "stun:stun.l.google.com:19302" }] };
if(typeof mozRTCPeerConnection === 'function') {
pc = new mozRTCPeerConnection(ice);
}
else {
console.log('google');
pc = new webkitRTCPeerConnection(ice);
}
pc.onicecandidate = function(event) {
console.log(event);
}
I expect that the 'onicecandidate' event will fire, but it doesn't work. I tried other public STUN servers as well, but nothing happens. So I assume there is probably something wrong with my comprehension :)
The PeerConnection won't start gathering candidates until you call setLocalDescription(); the information supplied to setLocalDescription tells PeerConnection how many candidates need to be gathered. (This behavior for setLocalDescription is indicated in its definition at http://tools.ietf.org/html/draft-ietf-rtcweb-jsep-03#section-4.2.4)
Here's what a complete flow looks like for establishing a connection between two PeerConnections in the same browser window (adding of MediaStreams omitted to focus on the signaling):
Since you included a mozPeerConnection in your question, I'll note that Firefox does not currently generate 'trickle candidates'. This means that it will include its candidate addresses as 'c' lines in the offer/answer, and the onicecandidate callback will never be called.
The downside to this approach is that Firefox must wait for all of its candidates to be gathered before creating its offer/answer (a process which can involve contacting STUN and TURN servers and waiting for either the responses or for the requests timeout).