Using WEBRTC to build front-end video chat room--Data channel Chapter

Source: Internet
Author: User
Tags rfc dtls

This article is translated from WEBRTC data channels

In two browsers, it is very complex to send messages for chat, games, or file transfers. Usually, we need to set up a server to forward the data, of course, the larger the size of the case, will be expanded into multiple data centers. In this case, there is a high latency and it is difficult to guarantee the privacy of the data.

These issues can be addressed through the Rtcdatachannel API provided by WEBRTC, which can transfer data directly between point-to-point. This article will show you how to create and use a data channel, and provide some common use cases on the network

To fully understand this article, you may need to understand some of the Rtcpeerconnection API's knowledge and how the Stun,turn and channels work. Highly recommended getting Started with WEBRTC this post

Why do we need another data channel?

We already have WebSocket, Ajax, and servers sending events, why do we need another communication channel? WebSocket are full-duplex, but these technologies are designed to communicate between the browser and the server.

Rtcdatachannel is a completely different approach:
* It can establish point-to-point interconnection through the rtcpeerconnection API. Because there is no need for a mediation server, the median "hop count" is reduced and the latency is lower.
* Rtcdatachannel uses the stream Control transmission Protocol (SCTP) protocol, allowing us to configure delivery semantics: We can configure the order of packet transfers and provide some configuration for retransmission.

SCTP-based Rtcdatachannel is already available in Chrome, opera, and Firefox on the desktop, while Android is supported on the mobile side.

A warning: signaling, stun and turn

Although WEBRTC allows point-to-point communication, it still requires a server:
* Signaling Transmission: Establishing a point-to-point connection requires the transmission of some media and network-related metadata information that needs to be passed through the server
* Nat and Firewall penetration: We need to create a network path between points and points through the ice framework. You can use the stun server (to determine the public access of both sides to your IP address and port) and the turn server (you must relay the data if the direct connection fails)

WebRTC in the real World:stun, TURN, and signaling the article details how WebRTC interacts with both of these servers

Function

The Rtcdatachannel API supports flexible data types. Its API is designed to mimic websocket and supports binary types such as BLOBs, Arraybuffer, and Arraybufferview in JavaScript, as well as string support. These types are important for file transfer and multi-player gaming.


Above from Ilya Grigorik's high performance Browser Networking

The Rtcdatachannel works correctly in unreliable mode (similar to UDP) or in reliable mode (similar to TCP). But the two modes are somewhat different:
* Reliable mode: Guaranteed message transmission must be successful, and guaranteed to arrive in order. This naturally requires a certain amount of overhead and is slower.
* Unreliable mode: There is no guarantee that message transmission will be successful, nor is it guaranteed to arrive sequentially. It eliminates those costs, and it's faster.

The efficiency of these two modes is similar in the case of no packet loss. However, in reliable mode, packet loss will cause all subsequent packets to be blocked, and the lost packets will be re-transmitted until they arrive successfully. Of course, we can use multiple data channels in the same application, each with their own reliability

The following shows how to configure the Rtcdatachannel of a reliable or unreliable mode

Configure the data channel

There have been many examples of rtcdatachannel on the Internet:
* SIMPL.INFO/DC
* Googlechrome.github.io/webrtc/dc1.html (SCTP or RTP)
* PUBNUB.GITHUB.IO/WEBRTC (two x PUBNUB users)

Ps:pubbub is a real-time information communication application development company

In this example, the browser creates a peering connection to itself. Then a data channel is created on this peering connection n, and some messages are sent. Finally, the message arrives successfully and appears on the page.

var peerconnection =New Rtcpeerconnection ();Creating a peer connection using a signaling transport channelvar Datachannel = Peerconnection.createdatachannel ("MyLabel", datachanneloptions);d atachannel.onerror =function  (Error) {console.log (" Data Channel error: ", error);}; Datachannel.onmessage = function console.log ( "Got Data Channel Message: ", event.data);}; Datachannel.onopen = function  () {datachannel.send ( "Hello world!");}; Datachannel.onclose = function  ( {console.log ( "the Data Channel is Closed");    

dataChannelobject is built on a peer connection that has already been created. It can be created before and after signaling transmission. In addition, you can assign a label to differentiate and provide a range of configuration options:

var dataChannelOptions = {  ordered: false, //不保证到达顺序  maxRetransmitTime: 3000, //最大重传时间};

We can add an maxRetransimits option (maximum retransmission count), but maxRetransimitTime or maxRetransimits only set one, not two sensible settings. If you want to use UDP, set maxRetransmits to 0, ordered for false . For more information, see RFC 4960 (SCTP) and RFC 3758 (SCTP partial reliability)
* Ordered: Whether the data channel guarantees sequential transmission of data
* Maxretrasmittime: Maximum retransmission time before information failure (forced into unreliable mode)
* Maxretransmits: Maximum number of retransmissions before information fails (forced into unreliable mode)
* Protocol: Allows a self-protocol to be used, but fails if the protocol is not supported
* Negotiated: If set to true, set the data channel of the other side automatically, that is, will use the same ID in their own configuration to establish a data channel with the other side
* ID: Provide a self-defined ID for the data channel

Is it safe?

In all components of WEBRTC, encryption is enforced. In Rtcdatachannel, all data uses datagram Transport Layer Security (DTLS). Dtls is the derivation of SSL, which means that your data will be as secure as using SSL-based connections. DTLS has been standardized and built into all browsers that support WEBRTC. If you need more information about DTLS, please visit Wireshark's wiki

Change the way you think about data

Processing large volumes of data has always been a difficult part of JavaScript. As Sharefest puts it, we need to think of data in a new way. If you need to transfer a file that is larger than your current available memory, you must consider the new way to save the information. This is also the meaning of technology such as filesystem API. We will cover the following

Build a file sharing app

Now we can create a file-sharing app with Rtcdatachannel. Applying the app to the Rtcdatachannel IQ also means that the transmitted file data will be encrypted and will not go through the server side of the application. Through this function, we can realize the interconnection between multi-users, and file sharing.

To successfully transfer a file, we need the following steps:
1. Reading file data via JavaScript's file API
2. Use Rtcpeerconnection to create a peer connection between users
3. Use Rtcdatachannel to create a data channel between users

There are other issues to consider when using Rtcdatachannel:
* File size : If the file is small and can be stored and read directly from a blob, then we can directly use the file API to read it into memory and send it through a reliable data channel (but it is important to note that the browser has a maximum transfer size limit). As the file gets bigger, it's not that simple. We need a chunking mechanism: The file will be divided into fragments, called Blocks of files. Instead of sending the entire file directly, we send a block of files at a time. Of course, the file block will have some metadata such as block ID, so that the other can be recognized. After the file block is received, the file blocks are first saved in the offline storage (for example, using the FileSystem API), and only when all the blocks are received, they are pieced together into the full file and saved to the user's hard disk.
* speed : File transfer is more suitable for use in reliable mode (like TCP) or non-reliable mode (like UDP) is debatable. If you apply knowledge to a simple pair of file transfers, using unreliable data channels will require the design of a certain response/retransmission protocol. You have to implement it yourself, and even if you are very good, it will still not be much faster than using reliable data transfer. A reliable and out-of-order data channel would be more appropriate, but if it was a multi-party file transfer, the results might be different.
* Block Size : These are the smallest "atomic" data in your app. There is currently a transfer size limit (although there may not be a limit later), so you have to block it. The maximum recommended block size is 16KB.

If the file has been fully transferred, it can be downloaded with a label:

function saveFile(blob) {  var link = document.createElement(‘a‘); link.href = window.URL.createObjectURL(blob); link.download = ‘File Name‘; link.click();};

There are currently two file-sharing applications that use this approach: Pubnub.github.io/rtc-pubnub-fileshare and Github.com/peer5/sharefest, both of which are open source, and provides rtcdatachannel-based file sharing

So what can we do?

Rtcdatachannel offers a whole new approach to file sharing, multiplayer, and content delivery applications:
* The point-to-point file transfer has been mentioned above
* Multiplayer games, combined with other technologies such as WEBGL, such as Mozilla's banana Bread
* Content delivery: A framework re-engineered by PEERCDN to provide resources for point-to-point communication

Change the way you build apps

Now we can use high-performance, low-latency rtcdatachannel to create better applications. Some frameworks, such as the Peerjs and PubNub WebRTC SDK, make rtcdatachannel easier to use, and its APIs are supported by various platforms

The advantages of Rtcdatachannel can change the idea of transferring data in your browser.

More information
      • Getting started with WebRTC
      • WebRTC in the real World:stun, TURN and signaling
      • WebRTC Resources
      • Working Draft
      • IETF WebRTC Data Channel Protocol Draft
      • How to send a File Using WebRTC Data API
      • 7 Creative Uses of WebRTC ' s Data Channel
      • Banana Bread 3D First person shooter game compiled to JS+WEBGL, using WebRTC data channels in multiplayer mode

Using WEBRTC to build front-end video chat room--Data channel Chapter

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.