webrtc實(shí)現(xiàn)局域網(wǎng)通話(三)

前言

先回顧一下上兩篇的內(nèi)容。第一篇,是調(diào)用攝像頭采集視頻的案例,首先創(chuàng)建了node.js 項(xiàng)目,然后用getUserMedia()這個(gè)東西獲取MediaStream,然后調(diào)用video.srcObject = mediasteam,瀏覽器就顯示采集內(nèi)容了。第二篇,是單機(jī)單個(gè)頁(yè)面呼叫的案例,主要目的是梳理信令轉(zhuǎn)發(fā)流程,核心點(diǎn)在于RTCPeerConnection()這個(gè)迷人的對(duì)象。
本篇將引入socket.io,實(shí)現(xiàn)兩臺(tái)電腦之間的呼叫的案例。
說(shuō)明:我現(xiàn)實(shí)情況是筆記本有攝像頭,而臺(tái)式機(jī)沒(méi)有,因此效果是筆記本采集視頻,臺(tái)式機(jī)上線后,筆記本呼叫臺(tái)式機(jī),然后臺(tái)式機(jī)顯示筆記本端采集的視頻。

好,下面進(jìn)入實(shí)際案例

客戶(hù)端

創(chuàng)建node.js項(xiàng)目,在項(xiàng)目文件下創(chuàng)建alice.html(呼叫者頁(yè)面)文件,代碼如下

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>alice</title>
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
        <div class="container">
            <h1>ailce</h1>
            <hr>
            <div class="video_container" align="center">
                <video id="local_video"  poster="img/video_fill.jpg" autoplay muted></video>
            </div>
            <hr>
            <button id="startButton">獲取本地視頻</button>
            <button id="callButton">呼叫bob</button>
            <button id="hangupButton">掛斷</button>
            <script src="/socket.io/socket.io.js"></script>
            <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
            <script src="js/alice.js"></script>
        </div>
    </body>
</html>

創(chuàng)建js文件夾,在其文件夾下創(chuàng)建alice.js文件,打開(kāi)文件鍵入如下代碼:

'use strict'

var localVideo = document.getElementById('local_video');

var startButton = document.getElementById('startButton');
var callButton = document.getElementById('callButton');
var hangupButton = document.getElementById('hangupButton');

var pc;
var localStream;
var socket = io.connect();

var config = {
    'iceServers': [{
        'urls': 'stun:stun.l.google.com:19302'
    }]
};

const offerOptions = {
    offerToReceiveVideo: 1,
    offerToReceiveAudio: 1
};

callButton.disabled = true;
hangupButton.disabled = true;

startButton.addEventListener('click', startAction);
callButton.addEventListener('click', callAction);
hangupButton.addEventListener('click', hangupAction);

function startAction() {
    navigator.mediaDevices.getUserMedia({ video: true, audio: true }).then(function (mediastream) {
        localStream = mediastream;
        localVideo.srcObject = mediastream;
        startButton.disabled = true;
    }).catch(function (e) {
        console.log(JSON.stringify(e));
    });
}

socket.on('create', function (room, id) {
    console.log('alice創(chuàng)建聊天房間');
    console.log(room + id);
});

socket.on('call', function () {
    callButton.disabled = false;
});

socket.on('signal', function (message) {
    if (pc !== 'undefined') {
        pc.setRemoteDescription(new RTCSessionDescription(message));
        console.log('remote answer');
    }
});

socket.on('ice', function (message) {
    if (pc !== 'undefined') {
        pc.addIceCandidate(new RTCIceCandidate(message));
        console.log('become candidate');
    }
});

socket.emit('create or join', 'room');

function callAction() {
    callButton.disabled = true;
    hangupButton.disabled = false;
    pc = new RTCPeerConnection(config);
    localStream.getTracks().forEach(track => pc.addTrack(track, localStream));
    pc.createOffer(offerOptions).then(function (offer) {
        pc.setLocalDescription(offer);
        socket.emit('signal', offer);
    });
    pc.addEventListener('icecandidate', function (event) {
        var iceCandidate = event.candidate;
        if (iceCandidate) {
            socket.emit('ice', iceCandidate);
        }
    });
}

function hangupAction() {

    localStream.getTracks().forEach(track => track.stop());
    pc.close();
    pc = null;
    hangupButton.disabled = true;
    callButton.disabled = true;
    startButton.disabled = false;

}

創(chuàng)建bob.html文件(被呼叫端頁(yè)面),編寫(xiě)如下代碼:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>對(duì)方的視頻</title>
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <link rel="stylesheet" href="css/main.css">
    </head>
    <body>
        <div class="container">
            <h1>對(duì)方的視頻</h1>
            <hr>
            <div class="video_container" align="center">
                <video id="remote_video" poster="img/video_fill.jpg" controls autoplay></video>
            </div>
            <hr>
            <script src="/socket.io/socket.io.js"></script>
            <script src="https://webrtc.github.io/adapter/adapter-latest.js"></script>
            <script src="js/bob.js"></script>
        </div>
    </body>
</html>

在js文件中創(chuàng)建bob.js文件,編寫(xiě)如下代碼:

'use strict'

var remoteVideo = document.getElementById('remote_video');

var socket = io.connect();

var config = {
    'iceServers': [{
        'urls': 'stun:stun.l.google.com:19302'
    }]
};

var pc;

socket.emit('create or join', 'room');

socket.on('join', function (room, id) {
    console.log('bob加入房間');
});

socket.on('signal', function (message) {
    pc = new RTCPeerConnection(config);
    pc.setRemoteDescription(new RTCSessionDescription(message));
    pc.createAnswer().then(function (answer) {
        pc.setLocalDescription(answer);
        socket.emit('signal', answer);
    });

    pc.addEventListener('icecandidate', function (event) {
        var iceCandidate = event.candidate;
        if (iceCandidate) {
            socket.emit('ice', iceCandidate);
        }
    });

    pc.addEventListener('addstream', function (event) {
        remoteVideo.srcObject = event.stream;
    });
});

socket.on('ice', function (message) {
    pc.addIceCandidate(new RTCIceCandidate(message));
});

至此,呼叫端和被呼叫端代碼編寫(xiě)完成。

信令轉(zhuǎn)發(fā)服務(wù)器

引入socket.io模塊(sockio.io是一個(gè)開(kāi)源的及時(shí)通訊框架)

npm install socket.io

新建index.js文件,編寫(xiě)如下代碼:

'use strict'

var express = require('express');
var app = express();

var http  = require('http').createServer(app);
var io = require('socket.io')(http);

app.use('/css',express.static('css'));
app.use('/js',express.static('js'));
app.use('/img',express.static('img'));

app.get('/',function(request,response){
    response.sendFile(__dirname +'/index.html');
});

app.get('/alice',function(request,response){
    response.sendFile(__dirname+"/alice.html")
});

app.get('/bob',function(request,response){
    response.sendFile(__dirname+"/bob.html")
});

io.on('connection',function(socket){
    console.log('有用戶(hù)加入進(jìn)來(lái)');
    socket.on('signal',function(message){
        socket.to('room').emit('signal',message);
    });

    socket.on('ice',function(message){
        socket.to('room').emit('ice',message);
    });

    socket.on('create or join',function(room){
        var clientsInRoom = io.sockets.adapter.rooms[room];
        var numClients = clientsInRoom ? Object.keys(clientsInRoom.sockets).length : 0;
        console.log(numClients);
        if(numClients===0){
            socket.join(room);
            socket.emit('create', room, socket.id);
            console.log('caller joined');
        }else if(numClients===1){
            socket.join(room);
            socket.to('room').emit('call');
            console.log('callee joined');
        }
    });
});

var server = http.listen(8080,function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log('listening on:http://s%:s%',host,port);
});

至此,案例代碼編寫(xiě)完成

測(cè)試結(jié)果

命令行 啟動(dòng)項(xiàng)目,打開(kāi)chrome,地址欄輸入localhost:8080/alice,打開(kāi)alice頁(yè)面(呼叫者),點(diǎn)擊獲取本地視頻按鈕,顯示內(nèi)容如下:

alice.png

打開(kāi)bob(被呼叫者)頁(yè)面,顯示內(nèi)容如下:

bob.png

被呼叫者上線后,呼叫者頁(yè)面呼叫按鈕可用,


call.png

點(diǎn)擊呼叫bob,顯示效果如下:

callee.png

總結(jié)

本章完成了局域網(wǎng)不同設(shè)備呼叫的案例。引入了socket.io框架,為信令轉(zhuǎn)發(fā)提供服務(wù),對(duì)信令轉(zhuǎn)發(fā)的認(rèn)識(shí)更加清晰了。在建立RTCPeerConnection()對(duì)象的時(shí)候,配置了iceServer,學(xué)名叫stun服務(wù),這是一個(gè)協(xié)助p2p連接的服務(wù)。搭建stun服務(wù),開(kāi)源項(xiàng)目有coturn。
下面將在局域網(wǎng)打通android手機(jī)端和筆記本之間的連接。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • feisky云計(jì)算、虛擬化與Linux技術(shù)筆記posts - 1014, comments - 298, trac...
    不排版閱讀 4,304評(píng)論 0 5
  • 單機(jī)版視頻呼叫 前端代碼 1、新建node.js項(xiàng)目,在項(xiàng)目文件夾下新建index.html打開(kāi),編寫(xiě)如下代碼: ...
    EarthNut閱讀 3,568評(píng)論 0 4
  • pyspark.sql模塊 模塊上下文 Spark SQL和DataFrames的重要類(lèi): pyspark.sql...
    mpro閱讀 9,911評(píng)論 0 13
  • 加密貨幣,特別是比特幣,幾乎從各個(gè)方面都得到了大量關(guān)注:規(guī)則、管理、稅務(wù)、技術(shù)、產(chǎn)品創(chuàng)新等等,不勝枚舉?!包c(diǎn)對(duì)點(diǎn)(...
    簡(jiǎn)聞閱讀 712評(píng)論 0 9
  • 咋天吃灑喝高了,睡的不醒耽誤更新了。 今天更新說(shuō)什么呢?就說(shuō)吃酒。 昨天吃的是青水花苗尚部的嫁女酒。種在竹子里的竹...
    歪才大白話閱讀 455評(píng)論 2 9

友情鏈接更多精彩內(nèi)容