Creating a peer connection
Next, we create a PeerConnection
object which encapsulates the connection to the remote peer.
Continue editing the Program.cs
file and append the following:
Create the peer connection object. Note that the
PeerConnection
class is marked as disposable, so must be disposed to clean-up the native resources. Failing to do so generally lead to crashes or hangs, as the internal WebRTC threads are not stopped and therefore the native DLL cannot be unloaded.using var pc = new PeerConnection();
This construct with the
using
keyword is a shorthand that will automatically callDispose()
when that variablepc
gets out of scope, in our case at the end of theMain
function.The
PeerConnection
object is initally created in an idle state where it cannot be used until initialized with a call toInitializeAsync()
. This method takes aPeerConnectionConfiguration
object which allows specifying some options to configure the connection. In this tutorial, most default options are suitable, but we want to specify a STUN server to make sure that the peer connection can connect to the remote peer even if behind a NAT.var config = new PeerConnectionConfiguration { IceServers = new List<IceServer> { new IceServer{ Urls = { "stun:stun.l.google.com:19302" } } } }; await pc.InitializeAsync(config);
In this example we use a free STUN server courtesy of Google. Note that this is fine for testing, but must not be used for production. Also, the ICE server list uses the
List<>
generic class, so we need to import theSystem.Collections.Generic
module with ausing
directive at the top of the file.using System.Collections.Generic;
Print a simple message to console to notify the user that the peer connection is initialized. This is optional, but is always good practice to inform the user after important steps completed, whether successfully or not.
Console.WriteLine("Peer connection initialized.");
Run the application again; the printed message should appear after some time. It generally takes up to a few seconds to initialize the peer connection, depending on the device.
Next : Adding local media tracks