websocket連通本地webrtc

來源:互聯網
上載者:User

標籤:else   error   http   通知   rem   ges   expr   參數   建立   

  最近各大直播網站都比較火,想探究一下是怎麼玩的。但是看了幾個大牛的回答,感覺有太多陌生的東西,嘗試起來成本略高。發現了有個東西叫webrtc,有人分析過他不適合做流量大,人數多的直播。但是我也只是玩一下,感受一下視頻連通的感覺。
  一開始在github上面看到了一個,比較全大部分的API都做了demo,還有canva 3d融合webrtc的例子。因為大部分例子都是沒有經過網路的通訊,所以想用socket寫一個交換信令的demo。其中也找到過demo但是沒試通過...然後看一些部落格和API自己寫一個小demo,協助理解webrtc
  目錄結構就是這樣  只拉取了express socket.io
     


     前端代碼:
     html部分
  

        <script src="/socket.io/socket.io.js"></script>          Local: <br>        <video id="localVideo" autoplay style="width:80px"></video><br>        Remote: <br>        <video id="remoteVideo" autoplay style="width:80px"></video>

 



  js部分

// 判斷髮起端              var isCaller = window.location.href.split(‘#‘)[1];            // 信令伺服器的Socket串連            var socket = io.connect(‘http://localhost:3000‘);            // stun和turn伺服器            var iceServer = null;            // iceServer在區域網路下可以通訊            var pc = new webkitRTCPeerConnection(iceServer);            // 發送給的其他端通知            pc.onicecandidate = function(event){                if (event.candidate !== null) {                    debugger                    console.log(‘onicecandidate -----‘);                    socket.emit(‘message‘,JSON.stringify({                        "event": "_ice_candidate",                        "data": {                            "candidate": event.candidate                        }                    }));                }            };            // 建立好p2p通道以後 會通過OnAddStream返回一個音視頻流的對象            pc.onaddstream = function(event){                document.getElementById(‘remoteVideo‘).src = URL.createObjectURL(event.stream);            };            // offer和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));            };            // 擷取本地音頻和視頻流            navigator.webkitGetUserMedia({                "audio": true,                "video": true            }, function(stream){                //在localVideo輸出音視頻                document.getElementById(‘localVideo‘).src = URL.createObjectURL(stream);                //把本地的媒體流綁定到PeerConnection                pc.addStream(stream);                //發起端 發送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){//處理socket請求                                if(event.type){                    console.log(‘請求以返回--------‘+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: ‘ + error);                    });                }                if(event.type==‘answer‘  && isCaller){                    pc.setRemoteDescription(event)                }                if(event.event==‘_ice_candidate‘){                    pc.addIceCandidate(new RTCIceCandidate(event.data.candidate));                }            })

  node部分

var express = require(‘express‘);var app = express()var server = require(‘http‘).Server(app);var io = 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){                var message=JSON.parse(data);        if(message.type){            console.log(message.type);        }else{            console.log(message.event);        }        console.log(‘請求已經廣播出去--------‘);        socket.broadcast.emit(‘message‘,message);                })    });

訪問localhost:3000開啟一個端  
然後訪問localhost:3000#true (開始進行對localhos:3000進行串連)

    下面具體流程轉載 煙雨任平生的

  • ClientA首先建立PeerConnection對象,然後開啟本地音視頻裝置,將音視頻資料封裝成MediaStream添加到PeerConnection中。
  • ClientA調用PeerConnection的CreateOffer方法建立一個用於offer的SDP對象,SDP對象中儲存當前音視頻的相關參數。ClientA通過PeerConnection的SetLocalDescription方法將該SDP對象儲存起來,並通過Signal伺服器發送給ClientB。
  • ClientB接收到ClientA發送過的offer SDP對象,通過PeerConnection的SetRemoteDescription方法將其儲存起來,並調用PeerConnection的CreateAnswer方法建立一個應答的SDP對象,通過PeerConnection的SetLocalDescription的方法儲存該應答SDP對象並將它通過Signal伺服器發送給ClientA。
  • ClientA接收到ClientB發送過來的應答SDP對象,將其通過PeerConnection的SetRemoteDescription方法儲存起來。
  • 在SDP資訊的offer/answer流程中,ClientA和ClientB已經根據SDP資訊建立好相應的音頻Channel和視頻Channel並開啟Candidate資料的收集,Candidate資料可以簡單地理解成Client端的IP地址資訊(本地IP地址、公網IP地址、Relay服務端分配的地址)。
  • 當ClientA收集到Candidate資訊後,PeerConnection會通過OnIceCandidate介面給ClientA發送通知,ClientA將收到的Candidate資訊通過Signal伺服器發送給ClientB,ClientB通過PeerConnection的AddIceCandidate方法儲存起來。同樣的操作ClientB對ClientA再來一次。
  • 這樣ClientA和ClientB就已經建立了音視頻傳輸的P2P通道,ClientB接收到ClientA傳送過來的音視頻流,會通過PeerConnection的OnAddStream回調介面返回一個標識ClientA端音視頻流的MediaStream對象,在ClientB端渲染出來即可。同樣操作也適應ClientB到ClientA的音視頻流的傳輸。


      具體流程可以參考:http://www.cnblogs.com/fangkm/p/4364553.html 他寫的比較細節,清新脫俗

websocket連通本地webrtc

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.