[WebRTC] 透過 WebRTC 做到P2P對談(3) – Client 連接、呼叫、被連入,對談篇

2017-03-02

上篇文章我們可以讓client 跟signaling server 聯繫,接來來就是要發出offer 跟收到 RTCIceCandidate 的過程,還有發送訊息。
image

其實最後發送訊息很簡單,這邊比較複雜的觀念就是,第一步 PERSON1 要先發出offer

//Offer 
//when somebody sends us an offer 
function handleOffer(offer, name) {
    //  alert(offer + name);
    console.log("handleOffer", offer + ",,," + name);
    connectedUser = name;
    yourConn.setRemoteDescription(new RTCSessionDescription(offer));

    //create an answer to an offer 
    yourConn.createAnswer(function (answer) {
        AddLog("createAnswer answer:" + answer, 'b');
        yourConn.setLocalDescription(answer);
        send({
            type: "answer",
            answer: answer
        });
    }, function (error) {;
        AddLog("Error when creating an answer" + error, 'r');
        // alert("Error when creating an answer");
    });

};

之後PERSON2 會收到 offer 並且server 這邊會互相的幫忙交換 candidate 這時候雙邊都會收到candidate
PERSON1:
Image 054

PERSON2 :
2017-03-02 17_17_54 的螢幕擷圖

基本上建議打開兩邊的開發者模式觀察log 跟 node.js 之間的互動 ,handleCandidate 的內容

//Candidate
//when we got an ice candidate from a remote user 
//被呼叫端收到邀請呼叫該func
function handleCandidate(candidate) {

    yourConn.addIceCandidate(new RTCIceCandidate(candidate));
    AddLog("Got Candidate(收到邀請) -" + JSON.stringify(candidate), 'b');
};

//Answer
//when we got an answer from a remote user 
function handleAnswer(answer) {
    yourConn.setRemoteDescription(new RTCSessionDescription(answer));
    AddLog("Got Answer(收到回應) -" + JSON.stringify(answer), 'b');
};

接下來就是送訊息,這就很簡單了

        //送出訊息
        $('#btnSend').click(function () {
            if ($('#txtContent').val().length > 0) {

                dataChannel.send($('#txtContent').val());
                AddLog('[' + name + ' 送出]' + $('#txtContent').val(), 'b');
            } else {
                AddLog('你沒有輸入', 'r');
            }

        });

撰寫到這邊,基本上可以直接把source code 拿來自己跑跑看就會懂她大概的流程,完成的頁面如下
2017-03-02 17_20_24 的螢幕擷圖

source code 在這邊
https://github.com/donma/SimepleWebRTCText

 

歡迎自行取用,記得如果你是用Visual Studio 跑執行,記得把防火牆打開不然之前兩台電腦測試都會被阻擋..


當麻許的超技八 2014 | Donma Hsu Design.