WebSocket connecting local WEBRTC

Source: Internet
Author: User
Tags emit

Recently the major live sites are compared to fire, want to explore how to play. But read a few Daniel's answer, feel there are too many unfamiliar things, try to get up a little higher cost. Found that there is a thing called WEBRTC, someone has analyzed he is not suitable for the flow of large numbers of live. But I'm just playing with it and feeling the video connectivity.
The first thing I saw on GitHub was a demo of all the APIs, and an example of Canva 3d Fusion WebRTC. Because most of the examples are not network communication, so want to use the socket to write an Exchange signaling demo. It also found a demo but did not try to pass ... Then watch some blogs and APIs to write a little demo to help understand WebRTC
The directory structure just pulled the express Socket.io


Front-End Code:
HTML section
  

        <Scriptsrc= "/socket.io/socket.io.js"></Script>  Local:<BR>        <VideoID= "Localvideo"AutoPlay Style= "width:80px"></Video><BR>Remote:<BR>        <VideoID= "Remotevideo"AutoPlay Style= "width:80px"></Video>



JS section

Determine the initiator var Iscaller = window.location.href.split (' # ') [1];            The socket connection of the signaling server is var socket = io.connect (' http://localhost:3000 ');            Stun and turn server var iceserver = null;            Iceserver can communicate var pc = new Webkitrtcpeerconnection (iceserver) under LAN;                    Other side notifications sent to Pc.onicecandidate = function (event) {if (event.candidate!== null) {                    Debugger Console.log (' onicecandidate-----');                            Socket.emit (' message ', json.stringify ({"Event": "_ice_candidate", "data": {                "Candidate": Event.candidate}));            }            }; When the peer channel is established, the object pc.onaddstream = function (event) {document.getelementbyi) will return a stream of audio and video via Onaddstream.            D (' Remotevideo '). src = Url.createobjecturl (event.stream); };            Offer and answer var SENDOFFERFN = function (desc) {pc.setlocaldescription (DESC);                Console.log (' offer-----');            Socket.emit (' message ', Json.stringify (DESC));                }, SENDANSWERFN = function (desc) {pc.setlocaldescription (DESC);                Console.log (' Answer-----');            Socket.emit (' message ', Json.stringify (DESC));            };            Get local audio and video stream Navigator.webkitgetusermedia ({"Audio": True, "video": True }, function (stream) {//in Localvideo output audio and video document.getElementById (' Localvideo '). src = URL.                Createobjecturl (stream);                Binds the local media stream to the Peerconnection Pc.addstream (stream);                        Initiator sends offer if (Iscaller) {pc.createoffer (SENDOFFERFN, function (Error) {           Console.log (' Failure callback: ' + error);         });            }}, function (Error) {console.log (' Getusermedia error: ' + error);            }); Socket.on (' message ', function (event) {//Processing socket request if (Event.type) {Console                . log (' request to return--------' +event.type);                }else{console.log ('--------') Console.log (event);                    } if (event.type== ' offer ' &&!iscaller) {pc.setremotedescription (event) Pc.createanswer (SENDANSWERFN, function (Error) {Console.log (' Failure callback: ' + E                    RROR);                });                } if (event.type== ' answer ' && iscaller) {pc.setremotedescription (event) } if (event.event== ' _ice_candidate ') {pc.addicecandidate (New Rtcicecandidate (event                . data.candidate));          }  }) 

Node section

varExpress = require (' Express ');varApp =Express ()varServer = require (' http '). Server (app);varIO = require (' Socket.io ') (server); Server.listen (3000); App.use (Express.static (__dirname+ '/js ')); App.get (‘/‘,function(req, res) {Res.sendfile (__dirname+ '/index.html ');}); Io.on (' Connection ',function(socket) {Socket.on (' Message ',function(data) {varMessage=json.parse (data); if(Message.type) {console.log (message.type); }Else{console.log (message.event); } console.log (' The request has been broadcast--------'); Socket.broadcast.emit (' Message ', message); })    });

Access localhost:3000 open one end
Then access localhost:3000#true (start connecting to localhos:3000)

The following specific process reproduced in the rain for any life

  • Clienta first creates the Peerconnection object, then turns on the local AV device, encapsulates the audio and video data into MediaStream and adds it to the peerconnection.
  • Clienta calls Peerconnection's Createoffer method to create an SDP object for an offer that holds the relevant parameters for the current audio and video in the SDP object. Clienta saves the SDP object through the Peerconnection Setlocaldescription method and sends it to CLIENTB via the signal server.
  • CLIENTB receives the offer SDP object sent by Clienta, which is saved by Peerconnection's Setremotedescription method, and call Peerconnection's Createanswer method to create an answer to the SDP object, The answer SDP object is saved by Peerconnection's Setlocaldescription method and sent to Clienta through the signal server.
  • Clienta receives the reply SDP object sent by CLIENTB and saves it through the Peerconnection setremotedescription method.
  • In the offer/answer process of SDP information, Clienta and CLIENTB have created appropriate audio channel and video channel based on SDP information and turned on the collection of candidate data. Candidate data can be simply understood as client IP address information (local IP address, public IP address, relay server assigned address).
  • When Clienta collects candidate information, Peerconnection will send a notification to Clienta via the Onicecandidate interface. Clienta will receive the candidate information by signal server sent to CLIENTB,CLIENTB through Peerconnection Addicecandidate method saved up. The same operation ClientB to Clienta again.
  • So Clienta and CLIENTB have established the audio and video transmission of the peer channel, CLIENTB received the Clienta transmitted over the audio and video stream, A MediaStream object that identifies the Clienta-side audio and video stream is returned via the Peerconnection Onaddstream callback interface, which is rendered on the ClientB side. The same operation also adapts to the transmission of CLIENTB to Clienta audio and video streams.


The specific process can be consulted: http://www.cnblogs.com/fangkm/p/4364553.html He wrote more details, fresh and refined

WebSocket connecting local WEBRTC

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.