Guía de WebRTC

1. Información general

Cuando dos navegadores necesitan comunicarse, normalmente necesitan un servidor en el medio para coordinar la comunicación, pasando mensajes entre ellos. Pero tener un servidor en el medio provoca un retraso en la comunicación entre los navegadores.

En este tutorial, aprenderemos sobre WebRTC, un proyecto de código abierto que permite que los navegadores y las aplicaciones móviles se comuniquen directamente entre sí en tiempo real. Luego lo veremos en acción escribiendo una aplicación simple que crea una conexión de igual a igual para compartir datos entre dos clientes HTML.

Usaremos HTML, JavaScript y la biblioteca WebSocket junto con el soporte WebRTC incorporado en los navegadores web para construir un cliente. Y crearemos un servidor de señalización con Spring Boot, utilizando WebSocket como protocolo de comunicación. Finalmente, veremos cómo agregar transmisiones de video y audio a esta conexión.

2. Fundamentos y conceptos de WebRTC

Veamos cómo se comunican dos navegadores en un escenario típico sin WebRTC.

Supongamos que tenemos dos navegadores y el navegador 1 necesita enviar un mensaje al navegador 2 . El navegador 1 lo envía primero al servidor :

Una vez que el servidor recibe el mensaje, lo procesa, encuentra el navegador 2 y le envía el mensaje:

Dado que el servidor tiene que procesar el mensaje antes de enviarlo al navegador 2, la comunicación se realiza casi en tiempo real. Por supuesto, nos gustaría que fuera en tiempo real.

WebRTC resuelve este problema creando un canal directo entre los dos navegadores, eliminando la necesidad del servidor :

Como resultado, el tiempo que lleva pasar mensajes de un navegador a otro se reduce drásticamente, ya que los mensajes ahora se enrutan directamente del remitente al receptor . También elimina el trabajo pesado y el ancho de banda incurridos por los servidores y hace que se comparta entre los clientes involucrados.

3. Soporte para WebRTC y funciones integradas

WebRTC es compatible con los principales navegadores como Chrome, Firefox, Opera y Microsoft Edge, así como con plataformas como Android e iOS.

WebRTC no necesita ningún complemento externo para ser instalado en nuestro navegador, ya que la solución viene incluida con el navegador.

Además, en una aplicación típica en tiempo real que involucra transmisión de video y audio, tenemos que depender en gran medida de las bibliotecas de C ++ y tenemos que manejar muchos problemas, que incluyen:

  • Ocultación de pérdida de paquetes
  • Cancelación del eco
  • Adaptabilidad del ancho de banda
  • Almacenamiento en búfer de fluctuación dinámica
  • Control de ganancia automática
  • Reducción y supresión de ruido
  • Imagen "limpieza"

Pero WebRTC maneja todas estas preocupaciones bajo el capó , lo que simplifica las comunicaciones en tiempo real entre clientes.

4. Conexión de igual a igual

A diferencia de una comunicación cliente-servidor, donde hay una dirección conocida para el servidor, y el cliente ya conoce la dirección del servidor para comunicarse, en una conexión P2P (peer-to-peer), ninguno de los pares tiene una dirección directa a otro compañero .

Para establecer una conexión de igual a igual, hay algunos pasos involucrados para permitir a los clientes:

  • estar disponibles para la comunicación
  • identificarse y compartir información relacionada con la red
  • compartir y acordar el formato de los datos, el modo y los protocolos involucrados
  • compartir datos

WebRTC define un conjunto de API y metodologías para realizar estos pasos.

Para que los clientes se descubran entre sí, compartan los detalles de la red y luego compartan el formato de los datos, WebRTC utiliza un mecanismo llamado señalización .

5. Señalización

La señalización se refiere a los procesos involucrados en el descubrimiento de la red, la creación de una sesión, la gestión de la sesión y el intercambio de metadatos de capacidad multimedia.

Esto es esencial ya que los clientes necesitan conocerse desde el principio para iniciar la comunicación.

Para lograr todo esto, WebRTC no especifica un estándar para la señalización y lo deja a la implementación del desarrollador. Por lo tanto, esto nos brinda la flexibilidad de usar WebRTC en una variedad de dispositivos con cualquier tecnología y protocolo de soporte.

5.1. Construyendo el servidor de señalización

Para el servidor de señalización, crearemos un servidor WebSocket usando Spring Boot . Podemos comenzar con un proyecto Spring Boot vacío generado a partir de Spring Initializr.

Para usar WebSocket para nuestra implementación, agreguemos la dependencia a nuestro pom.xml :

 org.springframework.boot spring-boot-starter-websocket 

Siempre podemos encontrar la última versión para usar de Maven Central.

La implementación del servidor de señalización es simple: crearemos un punto final que una aplicación cliente puede usar para registrarse como una conexión WebSocket.

Para hacer esto en Spring Boot, escribamos una clase @Configuration que amplíe WebSocketConfigurer y anule el método registerWebSocketHandlers :

@Configuration @EnableWebSocket public class WebSocketConfiguration implements WebSocketConfigurer { @Override public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) { registry.addHandler(new SocketHandler(), "/socket") .setAllowedOrigins("*"); } }

Note that we've identified /socket as the URL that we'll register from the client that we'll be building in the next step. We also passed in a SocketHandler as an argument to the addHandler method — this is actually the message handler that we'll create next.

5.2. Creating Message Handler in Signaling Server

The next step is to create a message handler to process the WebSocket messages that we'll receive from multiple clients.

This is essential to aid the exchange of metadata between the different clients to establish a direct WebRTC connection.

Here, to keep things simple, when we receive the message from a client, we will send it to all other clients except to itself.

To do this, we can extend TextWebSocketHandler from the Spring WebSocket library and override both the handleTextMessage and afterConnectionEstablished methods:

@Component public class SocketHandler extends TextWebSocketHandler { Listsessions = new CopyOnWriteArrayList(); @Override public void handleTextMessage(WebSocketSession session, TextMessage message) throws InterruptedException, IOException { for (WebSocketSession webSocketSession : sessions) { if (webSocketSession.isOpen() && !session.getId().equals(webSocketSession.getId())) { webSocketSession.sendMessage(message); } } } @Override public void afterConnectionEstablished(WebSocketSession session) throws Exception { sessions.add(session); } } 

As we can see in the afterConnectionEstablished method, we add the received session to a list of sessions so that we can keep track of all the clients.

And when we receive a message from any of the clients, as can be seen in the handleTextMessage, we iterate over all the client sessions in the list and send the message to all other clients except the sender by comparing the session id of the sender and the sessions in the list.

6. Exchanging Metadata

In a P2P connection, the clients can be very different from each other. For example, Chrome on Android can connect to Mozilla on a Mac.

Hence, the media capabilities of these devices can vary widely. Therefore, it's essential for a handshake between peers to agree upon the media types and codecs used for communication.

In this phase, WebRTC uses the SDP (Session Description Protocol) to agree on the metadata between the clients.

To achieve this, the initiating peer creates an offer that must be set as a remote descriptor by the other peer. In addition, the other peer then generates an answer that is accepted as a remote descriptor by the initiating peer.

The connection is established when this process is complete.

7. Setting Up the Client

Let's create our WebRTC client such that it can act both as the initiating peer and the remote peer.

We'll begin by creating an HTML file called index.html and a JavaScript file named client.js which index.html will use.

To connect to our signaling server, we create a WebSocket connection to it. Assuming that the Spring Boot signaling server that we built is running on //localhost:8080, we can create the connection:

var conn = new WebSocket('ws://localhost:8080/socket');

To send a message to the signaling server, we'll create a send method that will be used to pass the message in the upcoming steps:

function send(message) { conn.send(JSON.stringify(message)); }

8. Setting Up a Simple RTCDataChannel

After setting up the client in the client.js, we need to create an object for the RTCPeerConnection class. Here, we set up the object and enable the data channel by passing RtpDataChannels as true:

var peerConnection = new RTCPeerConnection(configuration, { optional : [ { RtpDataChannels : true } ] });

In this example, the purpose of the configuration object is to pass in the STUN (Session Traversal Utilities for NAT) and TURN (Traversal Using Relays around NAT) servers and other configurations that we'll be discussing in the latter part of this tutorial. For this example, it's sufficient to pass in null.

Now, we can create a dataChannel to use for message passing:

var dataChannel = peerConnection.createDataChannel("dataChannel", { reliable: true });

Subsequently, we can create listeners for various events on the data channel:

dataChannel.onerror = function(error) { console.log("Error:", error); }; dataChannel.onclose = function() { console.log("Data channel is closed"); };

9. Establishing a Connection With ICE

The next step in establishing a WebRTC connection involves the ICE (Interactive Connection Establishment) and SDP protocols, where the session descriptions of the peers are exchanged and accepted at both peers.

The signaling server is used to send this information between the peers. This involves a series of steps where the clients exchange connection metadata through the signaling server.

9.1. Creating an Offer

Firstly, we create an offer and set it as the local description of the peerConnection. We then send the offer to the other peer:

peerConnection.createOffer(function(offer) { send({ event : "offer", data : offer }); peerConnection.setLocalDescription(offer); }, function(error) { // Handle error here });

Here, the send method makes a call to the signaling server to pass the offer information.

Note that we are free to implement the logic of the send method with any server-side technology.

9.2. Handling ICE Candidates

Secondly, we need to handle the ICE candidates. WebRTC uses the ICE (Interactive Connection Establishment) protocol to discover the peers and establish the connection.

When we set the local description on the peerConnection, it triggers an icecandidate event.

This event should transmit the candidate to the remote peer so that the remote peer can add it to its set of remote candidates.

To do this, we create a listener for the onicecandidate event:

peerConnection.onicecandidate = function(event) { if (event.candidate) { send({ event : "candidate", data : event.candidate }); } };

The icecandidate event triggers again with an empty candidate string when all the candidates are gathered.

We must pass this candidate object as well to the remote peer. We pass this empty candidate string to ensure that the remote peer knows that all the icecandidate objects are gathered.

Also, the same event is triggered again to indicate that the ICE candidate gathering is complete with the value of candidate object set to null on the event. This need not be passed on to the remote peer.

9.3. Receiving the ICE Candidate

Thirdly, we need to process the ICE candidate sent by the other peer.

The remote peer, upon receiving this candidate, should add it to its candidate pool:

peerConnection.addIceCandidate(new RTCIceCandidate(candidate));

9.4. Receiving the Offer

After that, when the other peer receives the offer, it must set it as the remote description. In addition, it must generate an answer, which is sent to the initiating peer:

peerConnection.setRemoteDescription(new RTCSessionDescription(offer)); peerConnection.createAnswer(function(answer) { peerConnection.setLocalDescription(answer); send({ event : "answer", data : answer }); }, function(error) { // Handle error here });

9.5. Receiving the Answer

Finally, the initiating peer receives the answer and sets it as the remote description:

handleAnswer(answer){ peerConnection.setRemoteDescription(new RTCSessionDescription(answer)); }

With this, WebRTC establishes a successful connection.

Now, we can send and receive data between the two peers directly, without the signaling server.

10. Sending a Message

Now that we've established the connection, we can send messages between the peers using the send method of the dataChannel:

dataChannel.send(“message”);

Likewise, to receive the message on the other peer, let's create a listener for the onmessage event:

dataChannel.onmessage = function(event) { console.log("Message:", event.data); };

With this step, we have created a fully functional WebRTC data channel. We can now send and receive data between the clients. Additionally, we can add video and audio channels to this.

11. Adding Video and Audio Channels

When WebRTC establishes a P2P connection, we can easily transfer audio and video streams directly.

11.1. Obtaining the Media Stream

Firstly, we need to obtain the media stream from the browser. WebRTC provides an API for this:

const constraints = { video: true,audio : true }; navigator.mediaDevices.getUserMedia(constraints). then(function(stream) { /* use the stream */ }) .catch(function(err) { /* handle the error */ });

We can specify the frame rate, width, and height of the video using the constraints object.

The constraint object also allows specifying the camera used in the case of mobile devices:

var constraints = { video : { frameRate : { ideal : 10, max : 15 }, width : 1280, height : 720, facingMode : "user" } };

Also, the value of facingMode can be set to “environment” instead of “user” if we want to enable the back camera.

11.2. Sending the Stream

Secondly, we have to add the stream to the WebRTC peer connection object:

peerConnection.addStream(stream);

Adding the stream to the peer connection triggers the addstream event on the connected peers.

11.3. Receiving the Stream

Thirdly, to receive the stream on the remote peer, we can create a listener.

Let's set this stream to an HTML video element:

peerConnection.onaddstream = function(event) { videoElement.srcObject = event.stream; };

12. NAT Issues

In the real world, firewall and NAT (Network Address Traversal) devices connect our devices to the public Internet.

NAT provides the device an IP address for usage within the local network. So, this address is not accessible outside the local network. Without a public address, peers are unable to communicate with us.

To address this issue, WebRTC uses two mechanisms:

  1. STUN
  2. TURN

13. Using STUN

STUN is the simplest approach to this problem. Before sharing the network information to the peer, the client makes a request to a STUN server. The responsibility of the STUN server is to return the IP address from which it receives the request.

So, by querying the STUN server, we get our own public-facing IP address. We then share this IP and port information to the peer we want to connect to. The other peers can do the same to share their public-facing IPs.

To use a STUN server, we can simply pass the URL in the configuration object for creating the RTCPeerConnection object:

var configuration = { "iceServers" : [ { "url" : "stun:stun2.1.google.com:19302" } ] }; 

14. Using TURN

In contrast, TURN is a fallback mechanism used when WebRTC is unable to establish a P2P connection. The role of the TURN server is to relay data directly between the peers. In this case, the actual stream of data flows through the TURN servers. Using the default implementations, TURN servers also act as STUN servers.

TURN servers are publicly available, and clients can access them even if they are behind a firewall or proxy.

But, using a TURN server is not truly a P2P connection, as an intermediate server is present.

Nota: TURN es un último recurso cuando no podemos establecer una conexión P2P. A medida que los datos fluyen a través del servidor TURN, requiere mucho ancho de banda y no estamos usando P2P en este caso.

Similar a STUN, podemos proporcionar la URL del servidor TURN en el mismo objeto de configuración:

{ 'iceServers': [ { 'urls': 'stun:stun.l.google.com:19302' }, { 'urls': 'turn:10.158.29.39:3478?transport=udp', 'credential': 'XXXXXXXXXXXXX', 'username': 'XXXXXXXXXXXXXXX' }, { 'urls': 'turn:10.158.29.39:3478?transport=tcp', 'credential': 'XXXXXXXXXXXXX', 'username': 'XXXXXXXXXXXXXXX' } ] }

15. Conclusión

En este tutorial, discutimos qué es el proyecto WebRTC y presentamos sus conceptos fundamentales. Luego, creamos una aplicación simple para compartir datos entre dos clientes HTML.

También discutimos los pasos necesarios para crear y establecer una conexión WebRTC.

Además, analizamos el uso de servidores STUN y TURN como mecanismo de reserva cuando falla WebRTC.

Puede consultar los ejemplos proporcionados en este artículo en GitHub.