Panduan untuk WebRTC

1. Gambaran keseluruhan

Apabila dua penyemak imbas perlu berkomunikasi, mereka biasanya memerlukan pelayan di antara mereka untuk menyelaraskan komunikasi, menyampaikan mesej di antara mereka. Tetapi mempunyai pelayan di tengah mengakibatkan kelewatan komunikasi antara penyemak imbas.

Dalam tutorial ini, kita akan belajar mengenai WebRTC, sebuah projek sumber terbuka yang membolehkan penyemak imbas dan aplikasi mudah alih berkomunikasi secara langsung antara satu sama lain dalam masa nyata. Kemudian kita akan melihatnya dalam tindakan dengan menulis aplikasi sederhana yang membuat sambungan peer-to-peer untuk berkongsi data antara dua klien HTML.

Kami akan menggunakan HTML, JavaScript, dan perpustakaan WebSocket bersama dengan sokongan WebRTC bawaan dalam penyemak imbas web untuk membina klien. Dan, kami akan membina pelayan Isyarat dengan Spring Boot, menggunakan WebSocket sebagai protokol komunikasi. Akhirnya, kita akan melihat cara menambahkan aliran video dan audio ke sambungan ini.

2. Asas dan Konsep WebRTC

Mari lihat bagaimana dua penyemak imbas berkomunikasi dalam senario biasa tanpa WebRTC.

Andaikan kita mempunyai dua penyemak imbas, dan Penyemak Imbas 1 perlu menghantar mesej ke Penyemak Imbas 2 . Penyemak imbas 1 terlebih dahulu menghantarnya ke Pelayan :

Setelah Pelayan menerima mesej, ia memprosesnya, mencari Penyemak Imbas 2 , dan menghantarnya mesej:

Oleh kerana pelayan harus memproses mesej sebelum menghantarnya ke penyemak imbas 2, komunikasi berlaku dalam waktu hampir nyata. Sudah tentu, kita akan suka untuk menjadi pada masa nyata.

WebRTC menyelesaikan masalah ini dengan membuat saluran langsung antara kedua penyemak imbas, menghilangkan keperluan pelayan :

Akibatnya, waktu yang diperlukan untuk menyampaikan mesej dari satu penyemak imbas ke penyemak imbas yang lain berkurang secara drastik kerana sekarang mesej tersebut langsung menuju dari pengirim ke penerima . Ini juga menghilangkan pengangkatan dan lebar jalur yang dikeluarkan dari pelayan dan menyebabkannya dikongsi antara klien yang terlibat.

3. Sokongan untuk WebRTC dan Built-In Features

WebRTC disokong oleh penyemak imbas utama seperti Chrome, Firefox, Opera, dan Microsoft Edge, serta platform seperti Android dan iOS.

WebRTC tidak memerlukan plugin luaran untuk dipasang di penyemak imbas kami kerana penyelesaiannya dibundel dengan penyemak imbas.

Lebih jauh lagi, dalam aplikasi masa nyata yang biasa melibatkan penghantaran video dan audio, kita harus sangat bergantung pada perpustakaan C ++, dan kita harus menangani banyak masalah, termasuk:

  • Penyembunyian kehilangan paket
  • Pembatalan gema
  • Kesesuaian lebar jalur
  • Penyangga jitter dinamik
  • Kawalan keuntungan automatik
  • Pengurangan dan penindasan bising
  • Imej "pembersihan"

Tetapi WebRTC menangani semua kebimbangan ini , menjadikannya lebih mudah untuk membuat komunikasi masa nyata antara pelanggan.

4. Sambungan Rakan Sebaya

Tidak seperti komunikasi pelayan-pelanggan, di mana ada alamat yang diketahui untuk pelayan, dan pelanggan sudah mengetahui alamat pelayan untuk berkomunikasi, dalam hubungan P2P (peer-to-peer), tidak ada yang lain yang memiliki alamat langsung kepada rakan sebaya yang lain .

Untuk menjalin hubungan peer-to-peer, ada beberapa langkah yang diperlukan untuk membolehkan klien:

  • menyediakan diri mereka untuk komunikasi
  • saling mengenali dan berkongsi maklumat berkaitan rangkaian
  • berkongsi dan menyetujui format data, mod, dan protokol yang terlibat
  • berkongsi data

WebRTC menentukan sekumpulan API dan metodologi untuk melakukan langkah-langkah ini.

Agar klien dapat mengetahui satu sama lain, berkongsi butiran rangkaian, dan kemudian berkongsi format data, WebRTC menggunakan mekanisme yang disebut isyarat .

5. Isyarat

Pemberian isyarat merujuk kepada proses yang terlibat dalam penemuan rangkaian, pembuatan sesi, mengurus sesi, dan menukar metadata kemampuan media.

Ini penting kerana pelanggan perlu saling mengenali di hadapan untuk memulakan komunikasi.

Untuk mencapai semua ini, WebRTC tidak menetapkan standard untuk memberi isyarat dan membiarkannya dilaksanakan. Oleh itu, ini memberi kita fleksibiliti untuk menggunakan WebRTC pada pelbagai peranti dengan teknologi dan protokol sokongan.

5.1. Membina Pelayan Isyarat

Untuk pelayan isyarat, kami akan membina pelayan WebSocket menggunakan Spring Boot . Kita boleh mulakan dengan projek Spring Boot kosong yang dihasilkan dari Spring Initializr.

Untuk menggunakan WebSocket untuk pelaksanaan kami, mari tambahkan kebergantungan pada pom.xml kami :

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

Kita selalu dapat mencari versi terbaru untuk digunakan dari Maven Central.

Pelaksanaan pelayan isyarat adalah mudah - kami akan membuat titik akhir yang dapat digunakan oleh aplikasi klien untuk mendaftar sebagai sambungan WebSocket.

Untuk melakukan ini di Spring Boot, mari tulis kelas @Configuration yang meluaskan WebSocketConfigurer dan mengesampingkan kaedah 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.

Catatan: TURN adalah jalan terakhir apabila kami tidak dapat membuat sambungan P2P. Oleh kerana data mengalir melalui pelayan TURN, ia memerlukan lebar jalur yang banyak, dan kami tidak menggunakan P2P dalam kes ini.

Sama seperti STUN, kami dapat memberikan URL pelayan TURN dalam objek konfigurasi yang sama:

{ '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. Kesimpulannya

Dalam tutorial ini, kami membincangkan apa itu projek WebRTC dan memperkenalkan konsep asasnya. Kami kemudian membina aplikasi mudah untuk berkongsi data antara dua klien HTML.

Kami juga membincangkan langkah-langkah yang terlibat dalam membuat dan mewujudkan sambungan WebRTC.

Selanjutnya, kami melihat penggunaan pelayan STUN dan TURN sebagai mekanisme penggantian apabila WebRTC gagal.

Anda boleh melihat contoh yang diberikan dalam artikel ini di GitHub.