How to handle multiple WebRTC peer connections in a single client

Diana Cheung
2 min readOct 21, 2016

--

WebRTC is an open source library for establishing direct peer to peer connections between 2 browser clients to transfer live video and audio streams, as well as data via data channel.

Many of the tutorials available only illustrate 1 WebRTC connection per client or hardcoded multiple connections, for example peer1, peer2, peer3, etc. However, the question arises on how to dynamically create and manage multiple RTCPeerConnections per client. I encountered this obstacle when building out a JavaScript library that helped developers easily incorporate multiple broadcast live streams in a single display.

For context, the library used Socket.IO as the signaling mechanism, allowing for fast bidirectional communication between the server and clients, taking care of the passing of messages necessary in establishing a WebRTC connection.

In order for each client to keep track of who it is connected to, a data structure, in this case an object where the key is a unique identifier (the socket id of the remote peer) and value is the instantiated RTCPeerConnection, was utilized. So this data structure can hold many RTCPeerConnection instances, each identified by the socket id of the remote peer.

connections = {remotePeerId: RTCPeerConnection, ...};

When sending a message, such as an offer, to a remote peer, the signaling server appends the socket id (or any other unique identifier) of the local peer prior to relaying the message so that the remote peer can look up the appropriate RTCPeerConnection from the data structure to correctly set the Remote Description, generate the answer, and set the Local Description. The same logic applies to the messages relating to ICE candidates.

// server
socket.on('signal', (toId, message) => {
// relay the message to the recipient including the sender's id
io.to(toId).emit('signal', socket.id, message);
});
// client
connections[remotePeerId] = new RTCPeerConnection();
socket.on('signal', (fromId, message) => {
var currentConnection = connections[fromId];
if(currentConnection) {
if(message.type === 'answer') {
currentConnection.receiveAnswer(message.answer);
} else if (message.type === 'candidate') {
currentConnection.addCandidate(message.candidate);
}
}
});

Hope this article provided some clarifications on how to dynamically create and manage multiple WebRTC connections for each browser client!

--

--

Diana Cheung

Diana Cheung (ex-LinkedIn SW engineer, USC MBA) is a technical writer focused on dev tools and AI. She is an avid learner and has a soft spot for tea and meows.