What is an RTCPeerConnection?
The RTCPeerConnection API represents a WebRTC connection between multiple peers, for instance, the local computer and a remote peer and it's one of the essential concepts in the WebRTC call.
RTCPeerConnection
serves as the core interface that manages the entire lifecycle of a WebRTC connection. It acts as a bridge between your application and the underlying network protocols, handling the complex negotiations required to establish direct peer-to-peer communication. This API abstracts away the intricacies of network traversal, codec negotiation, and media transport, providing developers with a clean interface to build real-time communication applications.
The RTCPeerConnection interface encapsulates several critical WebRTC components working together seamlessly. It manages the signaling state machine that governs how peers exchange information about their capabilities and network conditions. Additionally, it coordinates with ICE agents to discover the best network paths between peers, handles DTLS encryption for secure communication, and manages SRTP for secure media transport.
RTCPeerConnection
allows you to establish a WebRTC calls to stream video and audio, and exchange data, and provide all necessary functionalities to make WebRTC calls, such as adding and displaying MediaStreamTracks (video and audio), creating SDP (session description protocol), and listening to ICE (Interactive Connectivity Establishment) candidates.
Beyond basic media streaming, RTCPeerConnection provides sophisticated media handling capabilities. It supports multiple media streams simultaneously, allowing applications to handle scenarios like screen sharing alongside camera feeds. The API also provides granular control over media tracks, enabling developers to mute, unmute, replace, or remove individual audio and video tracks during an active call. Furthermore, it includes built-in support for adaptive bitrate streaming, automatically adjusting video quality based on network conditions to maintain optimal user experience.
The peer connection also facilitates bidirectional data exchange through RTCDataChannel, enabling applications to send arbitrary data alongside media streams. This capability opens up possibilities for features like file sharing, real-time gaming, collaborative editing, and custom signaling protocols built on top of the reliable and ordered data transmission that WebRTC provides.
In this tutorial, you'll cover each step one by one and create a peer connection between two local and remote peers.
Create a Peer Connection
Basically, you can create a WebRTC peer connection using RTCPeerConnection API like the code below:
const peerConnection = new RTCPeerConnection();
While this basic instantiation works for simple scenarios, it creates a peer connection with default settings that may not be suitable for production environments. The default configuration typically includes no ICE servers, which means the connection will only work when both peers are on the same local network without any NAT traversal requirements. This limitation makes the basic approach primarily useful for development and testing scenarios.
You can also create a WebRTC peer connection by giving a configuration parameter, which provides the options to be set by specifying the new ICE server and its credentials like the example code below:
const rtcConfig = {
iceServers: [
{
urls: 'stun:stun.1.google.com:19302'
},
],
};
let peerConnection = new RTCPeerConnection(rtcConfig);
peerConnection
.createOffer({ iceRestart: true })
.then((offer) => pc1.setLocalDescription(offer))
..
The configuration object provides extensive customization options beyond just ICE servers. You can specify multiple STUN and TURN servers for redundancy, configure ICE candidate gathering policies, set bundle policies for media multiplexing, and define RTCP multiplexing preferences. Advanced configurations might include custom certificate handling for enhanced security, specific ICE transport policies to control candidate types, and connection constraints for bandwidth management.
ICE servers play a crucial role in establishing connectivity between peers located behind different networks. STUN servers help peers discover their public IP addresses and the type of NAT they're behind, while TURN servers act as relay points when direct peer-to-peer connection isn't possible. In production environments, it's recommended to configure multiple ICE servers from different providers to ensure maximum connectivity success rates.
This example creates a new RTCPeerConnection
which will use a STUN server at stun.1.google.com:19302 to negotiate connections. Then the ICE negotiation is restarted by invoking RTCPeerConnection.createOffer() method and giving true
for the iceRestart
option.
The ICE restart mechanism is particularly valuable in scenarios where network conditions change during an active call. This might occur when a user switches from WiFi to cellular data, experiences network congestion, or encounters firewall changes. By triggering an ICE restart, the peer connection attempts to discover new network paths and reestablish optimal connectivity without dropping the call entirely. The process involves gathering fresh ICE candidates and renegotiating the connection parameters while maintaining the existing media streams and data channels.
Close a Peer Connection
Once you don't need to maintain the peer connection anymore, you can close the WebRTC call with RTCPeerConnection.close() method. This method terminates the entire active streams and ongoing ICE processing and releases all connectivities and resources the connection uses.
Properly closing a peer connection is essential for resource management and preventing memory leaks in WebRTC applications. The close() method performs a comprehensive cleanup process that goes beyond simply stopping media streams. It closes all associated RTCDataChannels, stops all RTCRtpSenders and RTCRtpReceivers, terminates ICE gathering and checking processes, and releases all network resources including TURN allocations if they were being used.
The closing process follows a specific sequence to ensure graceful termination. First, all outgoing media tracks are stopped and their associated senders are closed. Then, any active data channels are closed, triggering their respective close events. The ICE agent stops gathering new candidates and terminates existing connectivity checks. Finally, all internal resources including codecs, network sockets, and buffer pools are released back to the system.
It's important to note that once a peer connection is closed, it cannot be reopened or reused. The connection transitions to a "closed" state permanently, and any attempts to perform operations on it will result in exceptions. For applications that need to reestablish connections, a new RTCPeerConnection instance must be created. Additionally, closing a peer connection doesn't automatically stop the media streams that were added to it; those need to be stopped separately if they're no longer needed, preventing continued access to user media devices like cameras and microphones.