分分鐘搞定P2P跨平臺通信,利用Agora實現

實現了ubuntu和web應用之間的跨平臺通信

提前準備技能:html,js,c++,linux

準備工作:下載Agora的兩個SDK,Web和Linux C++

下載地址:https://docs.agora.io/cn/Agora%20Platform/downloads

在ubuntu下編譯Linux C++的SDK,生成demo

運行:

./rtmServerDemo 8a9a81ca*******4f18afb1227e47c(自己的ID)

demo一部分代碼被我修改成中文了,當成註釋看吧

上前端代碼 Test.html:(將web sdk的js文件跟其放入同一個目錄下,並重命名爲AgoraSig.js)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Test</title>
    <script type="text/javascript" src="AgoraSig.js"></script>
    <script>
        const client=AgoraRTM.createInstance('8a9a81ca98f4430d84f18afb1227e47c');
        variable=new XMLHttpRequest();
        function msgInit() {
            client.on('ConnectionStateChanged', (newState, reason) => {
                console.log('on connection state changed to ' + newState + ' reason: ' + reason);
            });
            client.login({ token: null, uid: '12345' }).then(() => {
                console.log('AgoraRTM client login success');
            }).catch(err => {
                console.log('AgoraRTM client login failure', err);
            });
        }

        function sendMsg() {
            client.sendMessageToPeer({text: 'test peer message'}, '1234',)
                .then(sendResult => {
                    if (sendResult.hasPeerReceived) {
                        /* 遠端用戶收到消息的處理邏輯 */
                    } else {
                        /* 服務器已接收、但遠端用戶不可達的處理邏輯 */
                    }
                }).catch(error => {/* 發送失敗的處理邏輯 */
            });
        }
        
        function recvMsg(){
            client.on('MessageFromPeer', ({ text }, peerId) => { 
            // text 爲消息文本,peerId 是消息發送方 User ID
            /* 收到點對點消息的處理邏輯 */
            document.getElementById("myDiv").innerHTML=text;
            
            });
            
        }
    </script>
</head>
<body>
<input type="button" name="confirmAlter" value="init" οnclick="msgInit()"/>
<input type="button" name="confirmAlter" value="send" οnclick="sendMsg()"/>
<button type="button" οnclick="recvMsg()">recv</button>
<div>收到消息:</div>
<div id="myDiv"><h2>使用 AJAX 修改該文本內容</h2></div>
</body>
</html>

點擊init初始化,然後點擊 recv 進行消息接收(ajax),點send發送

 

放上成功測試圖:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章