Creating a RTCPeerConnection
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
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.
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:
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:
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.
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.