I'm working on implementing a distributed hash table using WebRTC and IndexedDB, and I ran into an issue I can't quite find the correct solution for. I have a simple application I've been using to explore WebRTC, and I'm successfully sending data over a data channel.
It would be impossible to keep a connection alive for every saved node, but it would also be unwieldy to re-signal every time. Normally for this you'd just keep an IP, port, and ID saved, but WebRTC needs more than that; below is the code I'm using to try to retrieve the connection, with information from the previous session stored in the "session" object:
function retrieve() {
console.log("Retrieving peer connection");
pc = new RTCPeerConnection(pcConfig);
pc.localStream = session.dataChannel;
pc.onicecandidate = () => {};
pc.onremovestream = (e) => console.log("Remote stream removed.");
if(initiator) {
pc.createOffer().then((sessionDescription) => {
pc.setLocalDescription(sessionDescription);
});
} else {
pc.createAnswer().then((sessionDescription) => {
pc.setLocalDescription(sessionDescription);
});
}
pc.setRemoteDescription(session.remoteDescription);
cands = session.candidates;
cands.map((cand) => {
pc.addIceCandidate(new RTCIceCandidate({
sdpMLineIndex: candidate.label,
candidate: candidate.candidate,
}));
});
}
This actually works, but it causes a few errors which I worry may indicate problems. The first of these occurs on both ends:
InvalidStateError: Cannot set remote answer in state stable
The second only occurs on the offering side, in my tests:
InvalidStateError: Cannot add ICE candidate when there is no remote SDP
For some reason, the data stream even works fine if I don't make an offer or answer at all, and just reinstate the candidates; the error in that case is the latter error on both sides.
What's going on here? Do I need to worry about it, or can I forge on? And as a side question, is this a silly way of solving this problem, with an obvious missed alternative?
Edit: I've now also tried a bunch of ways of reordering these steps, according to these errors, and haven't gotten much in the way of results; however, this sort of approach does allow real connections to reconnect and doesn't cause problems with the signaling even when I change networks on my phone, so I'll carry on testing the limits of this approach. I'd still like to know exactly what causes these errors, though, since they don't necessarily seem to indicate what they appear to indicate.