Insurance for a lot of correspondents chat with WebRTC wikis. How to organize WebRTC online broadcast using an additional webcam and VPS server Installing WebRTC Media & Broadcasting Server

Today, WebRTC is a hot technology for streaming audio and video in browsers. Conservative technologies, such as HTTP Streaming and Flash, are more suitable for distributing recorded content (video on demand) and significantly trade off WebRTC for real time and online broadcasts, then. where minimal video blurring is required, which allows viewers to watch what is seen on the live broadcast.

The ability to communicate clearly in real time is similar to the WebRTC architecture itself, where the transport of video streams uses the UDP protocol, which is the standard basis for transmitting video with minimal lag and is widely used in real-time communication systems.

Communication content is important in online broadcasting systems, webinars and other applications that require interactive communication with video content, end-users and require more.

Another reason to try WebRTC is, crazy, a trend. Today's skins Android Chrome browser It supports this technology, which guarantees millions of devices that are ready to watch the broadcast without installing any additional software or configuration.

In order to verify the WebRTC technology and launch a simple online broadcast on it, we used the server in the Flashphoner WebRTC Media & Broadcasting Server software. The features claim the ability to broadcast WebRTC streams in the “one-to-many” mode, as well as support for IP cameras and video surveillance systems via the RTSP protocol; In this regard, we focus on web-web broadcasts and their features.

Installation of WebRTC Media & Broadcasting Server

Bo for Windows system The server version did not appear, and I didn’t want to install a virtual machine like VMWare+Linux; I couldn’t protest the online broadcast on my home Windows computer. To save time, we decided to take an instance on a bad hosting on a platform like this:

This is Centos x86_64 version 6.5 without any pre-installed software in the Amsterdam data center. Thus, everything that we took into order was the server and ssh access to it. For those who know about console Linux commands Installing a WebRTC server is supposed to be simple and painless. Oh, what did they give us:

1. Explore archives:

$wget https://site/download-wcs5-server.tar.gz

2. Rozpakuvati:

$tar -xzf download-wcs5-server.tar.gz

3. Install:

$cd FlashphonerWebCallServer

Before installation, enter the server IP address: XXX.XXX.XXX.XXX

4. Activate license:

$cd /usr/local/FlashphonerWebCallServer/bin

$./activation.sh

5. Start WCS server:

$service webcallserver start

6. Check the log:

$tail - f /usr/local/FlashphonerWebCallServer/logs/flashphoner_manager.log

7. Please note that there are two processes in place:

$ps aux | grep Flashphoner

The installation process is completed.

Testing WebRTC online broadcast

Testing the broadcasts turned out to be quite simple. The core of the server is a web client, which consists of a dozen Javascript, HTML and CSS files that we downloaded into the /var/www/html folder at the installation stage. The only thing you need to do is to enter the IP address of the server in the flashphoner.xml config, so that the web client can establish a connection with the HTML5 Websockets server. Let us describe the testing process.

1. We open the test client page index.html in the Chrome browser:

2. To print the broadcast, you need to press the “Start” button in the middle of the screen.
Before you can start working, you need to make sure that the webcam is connected and ready for use. There are no special options for webcams; for example, we used the standard camera built into a laptop with a separate 1280x800 frame.

Chrome browser must ask for access to the camera and microphone in order to ensure that your video will be uploaded to the Internet server and allow it to be produced.

3. The interface successfully broadcasts the video stream from the camera to the WebRTC server. At the top right corner there is an indicator indicating that the stream is going to the server, at the bottom there is a “Stop” button for the video sending step.

Return respect to the message from the field below. Please enter a unique identifier for this stream so that someone can join it before re-watching it. Dosit to open this message in your browser. To copy it to the clipboard, you need to click on the “Copy” button.

With real add-ons for webinars, lectures, online video broadcasts or interactive TV, distributors will have to distribute this identifier to existing groups of viewers so that they can connect to the required streams in, but also logic robots programs. WebRTC Media & Broadcasting Server It doesn’t work, but only distributes videos.

5. The connection is installed and the viewer shows a stream on the screen. Now you can send a message to someone else, stop the flow or keep it quiet full screen mode, squeezing the controls at the lower right corner

Results of testing WebRTC server online broadcast

During the hour of testing, the backroom looked hopeless. The ping to the data center took about 100 milliseconds and the shutdown was invisible to the eye. You can assume that the actual delay is the same 100 plus or minus a few tens of milliseconds per hour of buffering. To compare with Flash video: such tests of Flash do not perform as well as WebRTC. So, if you move your hand at a similar level, the movement on the screen can only appear after one or two seconds.

However, it is important that cubes can be cut into pieces on the sides. This is indicative of the nature of the VP8 codec and its main goal is to ensure real-time video communications with pleasant clarity and without communication delays.

The server is easy to install and configured, for its launch you do not need any serious skills except a knowledge of Linux equal to that of a hacker who can enter commands from the console via ssh and log in text editor. As a result, we were able to improve one-to-many online broadcasting between browsers. Connecting additional watchers to the stream also did not cause any problems.

The quality of the broadcast turned out to be very pleasant for webinars and online communications. The only thing that the food called out was the video. The camera supports 1280x800, but the resolution on the test picture is similar to 640x480. Perhaps you should check the nutritional information with the distributors.

Video from testing broadcast from webcam
via WebRTC server

WebRTC (Web Real Time Communications) is a standard that describes the transmission of streaming audio, video and content from and to the browser in real time without installing plugins or other extensions. The standard allows you to switch the browser to the end terminal of the video conference and simply open the web page to print the download.

What is WebRTC?

This article will cover everything that an average consumer needs to know about WebRTC technology. Let's look at the advantages and disadvantages of the project, reveal some secrets, and understand where and why WebRTC is being developed.

What do you need to know about WebRTC?

The evolution of video communication standards and technologies

Sergiy Yutsaytis, Cisco, Video+Conference 2016

How does WebRTC work?

On the client side

  • Koristuvach opens the page to add the HTML5 tag
  • The browser grants access to the webcam and microphone of the user.
  • The JavaScript code on the client's website controls connection parameters (IP addresses and ports of the WebRTC server or other WebRTC clients) to bypass NAT and Firewall.
  • When you remove information about the browser or stream from a conference mixed on the server, the browser begins to accept the selected audio and video codecs.
  • The process of encoding and transferring streaming data between WebRTC clients begins (in our case, between the browser and the server).

On the WebRTC server side

To exchange data between two participants, a video server is not required, but if you need to combine several participants in one conference, a server is required.



The video server extracts media traffic from various devices, converting it and strengthening it for users, such as a terminal that uses WebRTC.

The WebRTC server also intercepts media traffic from WebRTC banquets and transmits it to conference participants, such as vikory programs for desktop computers or else mobile devices, there are times when such things are obvious.

Advantages to the standard

  • There is no need to install a PZ.
  • The bitterness of the connection is very high:
    • Search for current videos (VP8, H.264) and audio codecs (Opus).
    • Automatically adjusts the flow under the wash basin.
    • A noise reduction system has been introduced.
    • Automatic adjustment of microphone sensitivity level (AGC).
  • High level of security: all communications are protected and encrypted using TLS and SRTP protocols.
  • There is a mechanism for storing content, for example, on a desktop.
  • The ability to implement any control interface based on HTML5 and JavaScript.
  • The ability to integrate the interface with any back-end systems using WebSockets.
  • The project with the open source code can be distributed to your product or service.
  • True cross-platform: the same WebRTC add-ons will, however, work well on any operating system, desktop or mobile, as long as the browser supports WebRTC. It is important to save resources for developing software.

Not enough to standard

  • To organize group audio and video conferences, you need a video conferencing server that mixes video and sound from the participants, because The browser is unable to synchronize multiple streams that enter among themselves.
  • All WebRTC solutions are absurd among themselves, because... The standard means not only the methods of transmitting video and sound, but also the implementation of methods for addressing subscribers, increasing their availability, exchanging associated files, planning, etc., up to the vendor.
  • In other words, you will not be able to transfer the WebRTC programs of one distributor to the WebRTC applications of another distributor.
  • Mixing group conferences requires large financial resources, so this type of video communication requires purchases paid subscription Or invest in your own infrastructure, where each conference requires 1 physical core of a daily processor.

Secrets of WebRTC: how vendors can remove cost from disruptive web technology


Tsachi Levent-Levi, Bloggeek.me, Video+Conference 2015

WebRTC for market video conferencing

Increased number of video conferencing terminals

WebRTC technology has contributed to the development of the video conferencing market. After the emergence of the first browsers with the support of WebRTC in 2013, the number of video conferencing terminals around the world increased dramatically by 1 billion devices. In essence, the skin browser has become a video conferencing terminal, which does not compromise its hardware counterparts in terms of connection quality.

Search for specialized solutions

A combination of various JavaScript libraries and APIs of dark services with support for WebRTC allows you to easily add video support to any web projects. Previously, to transmit data in real time, distributors had to learn the principles of robotic protocols and use the practices of other companies, which often required additional licensing, which increased costs. WebRTC is now being actively promoted in services like “Call the site”, “Online chat support” and so on.

Ex-Koristuvacham Skype for Linux

In 2014, Microsoft announced support for the Skype for Linux project, which caused great frustration among IT workers. WebRTC technology is not tied to the operating system, but is implemented solely on the browser level. Linux users can use products and services based on WebRTC as a complete replacement for Skype.

Competition with Flash

WebRTC and HTML5 became a fatal blow to Flash technology, which was already experiencing its worst fate. Since 2017, wired browsers officially stopped supporting Flash, and the technology remained on the market. But it is necessary to introduce Flash more efficiently, even by creating a market for web conferencing and establishing the technical capabilities for live streaming in browsers.

Video presentations WebRTC

Dmitro Odintsov, TrueConf, Video+Conference Zhovten 2017

WebRTC codecs

Audio codecs

To compress WebRTC audio traffic, Opus and G.711 codecs are used.

G.711- the oldest voice codec with a high bitrate (64 kbps), which is most often stuck in systems traditional telephone. The main advantage is minimal computational gain through the use of light compression algorithms. The codec is changing low level compression of voice signals and do not introduce additional noise to the sound during the time of mixing between speakers.

G.711 is supported by a large number of devices. Systems that use this codec are more lightweight than those based on other audio codecs (G.723, G.726, G.728, etc.). For the G.711 box, taking away the score of 4.2 from the tested MOS (score between 4-5 is the highest and means garna yakist, similar to the transmission rate of voice traffic to ISDN and beyond).

Opus- This is a codec with low encoding latency (from 2.5 ms to 60 ms), supporting variable bitrate and high compression, which is ideal for transmitting streaming audio signals within variable bandwidth Istyu. Opus is a hybrid solution that combines the best characteristics of SILK (voice compression, human speech suppression) and CELT (audio encoding) codecs. The codec is available to the public, and publishers who are victorious about it do not need to pay legal fees. Compared with other audio codecs, Opus certainly wins for its richness in performance. You can download popular codecs with low bitrate, such as MP3, Vorbis, AAC LC. Opus renews the sound picture closest to the original, below AMR-WB and Speex. This codec is coming soon, and the creators of the WebRTC technology included it in the comprehensive range of audio standards that they are following.

Video codecs

The choice of video codec for WebRTC was taken from a number of retailers, with the result being H.264 and VP8. Almost everything current browsers support offending codecs. For video conference servers to work with WebRTC, it is enough to support only one.

VP8- a high-quality video codec with an open license, which offers high speed decoding of the video stream and increased stability before wasting frames. The codec is universal, it is easy to implement in hardware platforms, so vendors of video conferencing systems often use it in their products.

Paid video codec H.264 having become married to his brother-in-arms much earlier. This codec has a high degree of compression of the video stream while maintaining high video luminosity. The high codec width of hardware videoconferencing systems transmits video calls in the WebRTC standard.

Google and Mozilla are actively promoting the VP8 codec, and Microsoft, Apple and Cisco are promoting H.264 (to ensure compatibility with traditional video conferencing systems). And this is where the big problem arises for developers of the gloomy WebRTC solution, even if in the conference all participants use one browser, then the conference must be mixed once with one codec, and if browsers are different among them, then the conference happen twice different codecs, which should be moved twice system benefits to the media server and, as a result, the availability of subscriptions to WebRTC services.

WebRTC API

WebRTC technology is based on three main APIs:

  • (indicates that a web browser receives audio and video signals from cameras or the operator’s desktop).
  • RTCPeerConnection(indicates the connection between browsers to “exchange” images from the camera, microphone and desktop, media. Also, the “commitments” of this API include signal processing (cleaning up of third-party noise, adjusting microphone) and control over vikors audio and video codecs).
  • RTCData Channel(ensures two-way data transfer through the installed connection).

First, you deny access to the microphone and camera of the user, the browser will ask you to allow it. IN Google Chrome You can later set up access in the “Settings” section; in Opera and Firefox, the choice of devices can be selected immediately at the moment you revoke access from the list. The request for permission will appear always when using the HTTP protocol and once, if you are using HTTPS:


RTCPeerConnection. The browser that takes part in the WebRTC conference is responsible for its access to that object. With RTCPeerConnection, media from one browser to another can be routed through NAT and border screens. For successful transmission of media streams, participants must exchange such data using additional transport, such as web sockets:

  • the initiating participant sends to another participant an Offer-SDP (data structure, with characteristics of the media stream being transmitted);
  • another participant forms a “confirmation” - Answer-SDP and passes it on to the initiator;
  • Then an exchange of ICE candidates is organized between the participants, if they are detected (if the participants are behind NAT or border screens).

After the successful completion of the exchange between participants, the immediate transfer of media streams (audio and video) is organized.

RTCData Channel. Support for the Data Channel protocol has appeared in browsers recently, so this API can be seen in the WebRTC wiki in Mozilla Firefox 22+ and Google Chrome 26+ browsers. For additional assistance, participants can exchange text notifications in the browser.

Connections via WebRTC

Desktop browsers that we support

  • Google Chrome (17+) and all browsers based on the Chromium engine;
  • Mozilla FireFox (18+);
  • Opera (12+);
  • Safari (11+);

Supported mobile browsers for Android

  • Google Chrome (28+);
  • Mozilla Firefox (24+);
  • Opera Mobile (12+);
  • Safari (11+).

WebRTC, Microsoft and Internet Explorer

Microsoft has been saving money on the WebRTC support drive for a long time Internet Explorer and in your new Edge browser. The boys from Redmond no longer like to put technology into the hands of corporate owners, since they cannot control it, the axis of this policy. Ale stepwise destroyed from a dead center on the right, because. It is no longer possible to ignore WebRTC, and the ORTC project, similar to the WebRTC standard, has been announced.

In the words of the ORTC developers - this is an extension to the WebRTC standard with a reduced set of APIs for JavaScript basics And HTML5, which in my original translation means that everything will be the same, only Microsoft, not Google, will control the standard and its developments. A set of extension codecs supported by H.264 and various audio codecs of the G.7XX series, which are used in telephony and hardware video conferencing systems. It is possible that RDP support (for content transfer) and message exchange is required. Before speaking, Internet Explorer has not been kind to the koristuvachs, the ORTC support will be deprived of Edge. Well, naturally, such a set of protocols and codecs has little connection with Skype for Business, which creates even more business stagnation for WebRTC.

WebRTC(Web Real-Time Communications) is a technology that allows Web add-ons and sites to seamlessly transmit audio and/or video media streams, as well as exchange additional data between browsers, without the hassle of intermediaries. A set of standards, including WebRTC technology, allows you to exchange data and conduct peer-to-peer teleconferences without the need to install plugins or other third-party software.

WebRTC consists of many interdependent application program interfaces (APIs) and protocols that operate simultaneously. The documentation you'll find will help you understand the basics of WebRTC, how to set up and configure connections for data transfer, media streaming, and much more.

Crazyness

Since the implementation of WebRTC is in the process of development and your browser has WebRTC functionality, we recommend that you use the Adapter.js polyfile library from Google before working on your code.

Adapter.js provides a variety of wedges and polyfills for the smooth integration of features in WebRTC implementations among contexts that support it. Adapter.js also collects the prefixes of the generators, and other names of authorities, making the development process on WebRTC easier, with the greatest result. The library is also available as an NPM package.

For further development of the Adapter.js library, we marvel.

I understand that WebRTC wiki

WebRTC has many purposes, providing advanced multimedia capabilities for the Web, including support for audio and video conferences, file sharing, screen sharing, authentication and interoperability. legacy telephone systems, including support for DTMF tone dialing. Connections between nodes can be created without the need for special drivers or plugins, and often without intermediate services.

The connection between two nodes is represented as an object to the RTCPeerConnection interface. As long as the connection is installed openly, the RTCPeerConnection vikorist object, media streams (MediaStreams) and/or data channels (RTCDataChannel s) can be added to the connection.

Media streams can be composed of any number of tracks (tracks) of media information. These tracks are represented by objects in the MediaStreamTrack interface and can contain one or more types of media, including audio, video, text (such as subtitles or chapter titles). Most streams are formed, at a minimum, from only one audio track (one audio track), or video tracks, and can be sent and removed, like streams (media data at a given time) or saving u file.

It is also possible to connect between two nodes to exchange data using the RTCDataChannel interface object, which can be used to transmit service information, exchange data, Game statuses, file transfer or closed data transfer channels.

more details and links to relevant guides and tutorials needed

WebRTC interfaces

Through those that WebRTC provides interfaces that work seamlessly for the execution of various tasks, we divided them into categories. Follow the alphabet on the sidebar for quick navigation.

Adjustment of connection and keruvannya

These interfaces are selected for configuration, support and networking with WebRTC connections. They represent simultaneous media connections, data channels, and interfaces that are used when exchanging information about the capabilities of the skin node, to select the best configuration when installing two-way multimedia great connection.

RTCPeerConnection Represents WebRTC connection between local computer and at a distant node. Vikoryst is used to process a successful transfer between two nodes. RTCSessionDescription Specifies session parameters. The RTCSessionDescription code contains a description of the type that shows each part (proposition/conversation) of the negotiation process and describes the SDP descriptor of the session. RTCIceCandidate is the Internet Connection Installation (ICE) server candidate for installing the RTCPeerConnection connection. RTCIceTransport Provides information about your Internet connection (ICE). RTCPeerConnectionIceEvent Represents the events that are selected for ICE candidates called RTCPeerConnection . One type is passed to this pod object: icecandidate . RTCRtpSender handles the transmission of data through an object of type MediaStreamTrack for an object of type RTCPeerConnection. RTCRtpReceiver Receives and decodes data through an object of type MediaStreamTrack for an object of type RTCPeerConnection. RTCTrackEvent Indicates that a new input object of type MediaStreamTrack is created and an object of type RTCRtpReceiver is added to the RTCPeerConnection object. RTCCertificate Provides a certificate that represents the RTCPeerConnection object. RTCDataChannel Represents a bidirectional data channel between two communication nodes. RTCDataChannelEvent Displays events that occur when an object of the RTCDataChannel type is connected to an object of the RTCPeerConnection datachannel type. RTCDTMFSender Encodes and transmits dual-tone multi-frequency (DTMF) signaling for an object of type RTCPeerConnection. RTCDTMFToneChangeEvent Indicates the Dual Tone Multi Frequency (DTMF) tone change input. This product does not drain (as not otherwise designated) or touch (as not otherwise designated). RTCStatsReport Asynchronously reports the status for the transferred object to the MediaStreamTrack type. RTCIdentityProviderRegistrar Registers an identity provider (idP). RTCIdentityProvider Enables the browser's ability to request the creation or verification of an identified identity. RTCIdentityAssertion Displays the ID of the remote streaming node. If the university is not yet installed and confirmed, the message sent to the interface is turned to null . Once installed, it cannot be changed. RTCIdentityEvent Represents an identity provider (idP) identifier object. Similar to the object type RTCPeerConnection. One type is passed to this sub-identityresult. RTCIdentityErrorEvent Represents an error event associated with an identity provider (idP). Similar to the object type RTCPeerConnection. Two types of errors are transmitted by this method: idpassertionerror and idpvalidationerror.

Pos_bniki

An overview of the WebRTC architecture API, which is used by developers to create and develop WebRTC, and expand the dialing edge protocols and standards of connection. This look is a showcase of these standards. WebRTC allows you to organize a connection in the host-to-host mode for transmitting additional data, audio, video streams or any other combination in the browser. In this article, we will take a look at the life of a WebRTC session, starting with the establishment of a connection and we will go through the entire process until completion, when it is no longer needed. Overview of the WebRTC API WebRTC consists of many interdependent application program interfaces (APIs) and protocols that run together to support the exchange of data and media streams between two or more nodes. This is the statistic of representations short look cutaneous API and yaku meta vin reexamines. WebRTC Basics This article will walk you through the creation of cross-browser RTC programs. Until the end of this article, the working date is the media channel that operates in point-to-point mode. WebRTC protocols This article presents protocols, in addition to which the WebRTC API was created. This handbook describes how you can vikorist the connection of vuzol-vuzol and knitting

WebRTC is an API that is provided by the browser and allows you to organize P2P connections and transfer data directly between browsers. On the Internet, you can get a lot of help from writing a powerful video chat using WebRTC. For example, the axis of the article is on Habré. All this is done between two clients. In this article I will try to learn about how to organize connections and exchange of information between three and more clients using WebRTC.

The RTCPeerConnection interface is a peer-to-peer connection between two browsers. In order to bring together three or more co-workers, we will have to organize a mesh boundary (a boundary between which node connects to all other nodes).
Let's use the following diagram:

  1. When the page is open, the presence of the room ID is checked location.hash
  2. If the room ID is not specified, a new one is generated
  3. The signalling server is powered by notification of those who want to join the specified room
  4. The Signalling server sends notifications about a new customer to other clients in this room.
  5. Clients who are already in the room, send new SDP offer
  6. Newbie responds to offer" and

0. Signaling server

Apparently, although WebRTC provides the ability to P2P connection between browsers, its work requires additional transport for exchanging service messages. Which application uses this transport is a WebSocket server, written in Node.JS with the socket.io wiki:

Var socket_io = require("socket.io"); module.exports = function (server) ( var users = (); var io = socket_io(server); io.on("connection", function(socket) ( // It's time for the new customer to get to room socket.on("room ) ", function(message) ( var json = JSON.parse(message); // Add the socket to the list of clients users = socket; if (socket.room !== undefined) ( // If the socket is already in which room) , exit from it socket.leave(socket.room);) // Log in to the requested room socket.room = json.room; socket.join(socket.room); socket.user_id = json.id; adding a new participant socket.broadcast.to(socket.room).emit("new", json.id); // Announcement related to WebRTC (SDP offer, SDP answer or ICE candidate) socket.on ("webrtc", function(message) ( var json = JSON.parse(message); if (json.to !== undefined && users !== undefined) ( // The owner of the owner is indicated in the message) to the server , we send messages only to you... users.emit("webrtc", message); ) else ( // ...information is also important for broadband socket.broadcast.to(socket.room).emit("webrtc", message); ) )); // Once there is a connection socket.on("disconnect", function() ( // When a client is connected, we notify about others socket.broadcast.to(socket.room).emit("leave", socket.user_id ); delete users;)); )); );

1.index.html

The exit code for the page is simple. I obviously did not pay respect to the layout of other beauties, which is not what this article is about. If anyone wants to make it beautiful, there are no special difficulties.

WebRTC Chat Demo

Connected to 0 peers

2. main.js

2.0. Extracting the message on the elements of the page and the WebRTC interface
var chatlog = document.getElementById("chatlog"); var message = document.getElementById("message"); var connection_num = document.getElementById("connection_num"); var room_link = document.getElementById("room_link");

We, as before, have to use browser prefixes to adapt to WebRTC interfaces.

Var PeerConnection = window.mozRTCPeerConnection || window.webkitRTCPeerConnection; var SessionDescription = window.mozRTCSessionDescription || window.RTCSessionDescription; var IceCandidate=window.mozRTCIceCandidate || window.RTCIceCandidate;

2.1. Designated room ID

Here we need a function to create a unique identifier for the room and guest. We will be victorious for this UUID.

Function uuid() ( var s4 = function() ( return Math.floor(Math.random() * 0x10000).toString(16); ); return s4() + s4() + "-" + s4() + "-" + s4() + "-" + s4() + "-" + s4() + s4() + s4();

Let's try to extract the room ID from the address. If this is not installed, a new one will be generated. We are displayed on the page of sending to the production room, and at the same time the ID of the production process operator is generated.

Var ROOM = location.hash.substr(1); if (!ROOM) ( ROOM = uuid(); ) room_link.innerHTML = "Link to the room"; var ME = uuid();

2.2. WebSocket

As soon as the page is open, connecting to our signaling server, it will promptly ask for the input to the room and, perhaps, the requestors will be notified.

// It is indicated that when a message is closed, it is necessary to send an alert to the server about it var socket = io.connect("", ("sync disconnect on unload": true)); socket.on("webrtc", socketReceived); socket.on("new", socketNewPeer); // It will forcefully ask the input to the room socket.emit("room", JSON.stringify((id: ME, room: ROOM))); // Additional function for boosting address notifications related to WebRTC function sendViaSocket(type, message, to) ( socket.emit("webrtc", JSON.stringify((id: ME, to: to, type: type, data : message) )));

2.3. PeerConnection settings

Most providers provide connections to the Internet via NAT. Through this direct connection it becomes not such a trivial matter. Once the connection is created, we need to specify a list of STUN and TURN servers, so that the browser can be used to bypass NAT. There are also a couple of additional options for connection.

Var server = ( iceServers: [ (url: "stun:23.21.150.121"), (url: "stun:stun.l.google.com:19302"), (url: "turn:numb.viagenie.ca", credential: "you can read your words", username: " [email protected]") ] ); var options = ( optional: [ (DtlsSrtpKeyAgreement: true), // required for communication between Chrome and Firefox (RtpDataChannels: true) // required by Firefox for the DataChannels API ] )

2.4. Connection of a new account manager

When a new banquet arrives in the room, the server forces us to notify new. Please be aware of the information you have entered and the function will be clicked. socketNewPeer.

Var peers = (); function socketNewPeer(data) ( peers = (candidateCache: ); // Create a new connection var pc = new PeerConnection(server, options); // Initialize it initConnection(pc, data, "offer"); // Save the peer to the list peers.connection = pc;// Create a DataChannel for which information will be exchanged var channel = pc.createDataChannel("mychannel", ());channel.owner=data;peers.channel=channel; channel bindEvents(channel) ; // Create an SDP offer pc.createOffer(function(offer) ( pc.setLocalDescription(offer); )); function initConnection(pc, id, sdpType) if (event.candidate) ( // When a new ICE candidate is identified, it is added to the list for further sending peers.candidateCache.push(event.candidate); else ( // If the identification of candidates is completed, the searcher will be searched again, but without a candidate // For which type we send the banquet to the first SDP offer or SDP answer (independent of the function parameter)... sendViaSocket(sdpType, pc.localDescription, id); // ...and then all candidates found before ICE for (var i = 0; i< peers.candidateCache.length; i++) { sendViaSocket("candidate", peers.candidateCache[i], id); } } } pc.oniceconnectionstatechange = function (event) { if (pc.iceConnectionState == "disconnected") { connection_num.innerText = parseInt(connection_num.innerText) - 1; delete peers; } } } function bindEvents (channel) { channel.onopen = function () { connection_num.innerText = parseInt(connection_num.innerText) + 1; }; channel.onmessage = function (e) { chatlog.innerHTML += "

Peer says: "+e.data+"
"; }; }

2.5. SDP offer, SDP answer, ICE candidate

When you select one of these notifications, you will be prompted for a notification.

Function socketReceived(data) ( var json = JSON.parse(data); switch (json.type) ( case "candidate": remoteCandidateReceived(json.id, json.data); break; case "offer": remoteOfferReceived(json. ) id, json.data); break; case "answer": remote

2.5.0 SDP offer
function remoteOfferReceived(id, data) ( createConnection(id); var pc = peers.connection; pc.setRemoteDescription(new SessionDescription(data)); pc.createAnswer(function(answer) ( pc.setLocalDescription(answer); )); ) function createConnection(id) ( if (peers === undefined) ( peers = (candidateCache: ); var pc = new PeerConnection(server, options); initConnection(pc, id, "answer"); peers.connection = pc pc.ondatachannel = function(e) ( peers.channel = e.channel; peers.channel.owner = id; bindEvents(peers.channel); ) ) )
2.5.1 SDP response
function remoteAnswerReceived(id, data) ( var pc = peers.connection; pc.setRemoteDescription(new SessionDescription(data)); )
2.5.2 ICE candidate
function remoteCandidateReceived(id, data) ( createConnection(id); var pc = peers.connection; pc.addIceCandidate(new IceCandidate(data)); )
2.6. Sending a notification

When pressing the button Send function is called sendMessage. All you have to do is follow the list of banquets and try to send notifications to everyone.

Meta of these articles – using a demonstration of peer-to-peer video chat (p2p video chat), get acquainted with its structure and operating principle. For this purpose, we will quickly provide coverage to a large number of clients with a demonstration of the peering video chat webrtc.io-demo. You can download it for free: https://github.com/webRTC/webrtc.io-demo/tree/master/site.

Please note that GitHub is a website or a web service for the comprehensive development of Web projects. On this site, developers can place the codes of their projects, discuss them and compare them one by one. In addition, large IT companies post official repositories on this site. The service is cost-free for projects with an open source code. GitHub is a collection of libraries with open source code.

Also, download a demo of peer-to-peer video chat from GitHub and place it on the C drive of your personal computer in the directory created for our webrtc_demo add-on.


Rice. 1

As follows from the structure (Fig. 1), peer-to-peer video chat consists of client script.js and server server.js scripts implemented by my JavaScript program. Script (library) webrtc.io.js (CLIENT) - ensures the organization of real-time communication between browsers using a peer-to-peer scheme: "client-client", and webrtc.io.js (CLIENT) and webrtc.io.js (SERVER), Using the WebSocket protocol, ensure duplex communication between the browser and the web server using the client-server architecture.

The script webrtc.io.js (SERVER) is included in the webrtc.io library and is located in the node_modules\webrtc.io\lib directory. Video chat interface index.html implemented in HTML5 and CSS3. Instead of files, the webrtc_demo program can be viewed using one of the html editors, such as Notepad++.

The principle of video chat work can be verified in file system PC. To run the server (server.js) on your computer, you need to install the node.js middleware. Node.js allows you to run JavaScript code in the browser. You can download node.js as follows: http://nodejs.org/ (version v0.10.13 as of 07/15/13). On the main page of the node.org website, click on the download button and go to http://nodejs.org/download/. For koristuvachiv windows First install win.installer (.msi), then run win.installer (.msi) on the PC, then install nodejs and “npm package manager” in the Program Files directory.




Rice. 2

Thus, node.js consists of the core development and development of JavaScript code, as well as a set of internal modules that can be installed with the help of a manager or package manager npm.

To install modules you need to command line From the programs directory (for example, "webrtc_demo") enter the command: npm install module_name. During the process of installing modules, the npm manager creates the node_modules folder in the directory where the installation was completed. For the process, nodejs automatically includes modules in the node_modules directory.

Also, after installing node.js, open the command line and open the express module in the node_modules directory webrtc_demo using the npm package manager:

C:\webrtc_demo>npm install express

The express module is a web framework for node.js or a web platform for developing programs. To achieve global access to express, you can install it like this: npm install -g express.

Then we update the webrtc.io module:

C:\webrtc_demo>npm install webrtc.io

Then in the command line we launch the server: server.js:

C:\webrtc_demo>node server.js


Rice. 3

The entire server is running successfully (Figure 3). Now, using a web browser, you can go to the server behind the IP address and access the web page index.html, from which the web browser will receive the client script code - script.js and the script code webrtc.io.js, and then delete them. To operate a peer-to-peer video chat (to establish a connection between two browsers), you need two browsers that support webrtc, connect by IP address to the signal server that runs on node.js.

As a result, the interface of the client part of the communication program (video chat) opens and allows access to the camera and microphone (Fig. 4).



Rice. 4

After clicking on the “Allow” button, the camera and microphone are connected for multimedia recording. In addition, through the video chat interface you can collect text data (small 5).



Rice. 5

It is necessary to note that... The server is a signal server and is mainly used for establishing connections between browsers of computer users. For the server script server.js, which provides WebRTC signaling, Node.js is used.