3分鍾實現網頁版多人文本、視頻聊天室 (含完整源碼)


基於SimpleWebRTC快速實現網頁版的多人文本、視頻聊天室。

 

1 實現方法

復制下面的代碼,保存為一個html文件

<!DOCTYPE html>
<html>
<head>
    <script src="https://code.jquery.com/jquery-1.9.1.js"></script>
    <script src="http://simplewebrtc.com/latest.js"></script>
    <script>
 
        var webrtc = new SimpleWebRTC({
            // the id/element dom element that will hold "our" video
            localVideoEl: 'localVideo',
            // the id/element dom element that will hold remote videos
            remoteVideosEl: 'remoteVideos',
            // immediately ask for camera access
            autoRequestMedia: true,
            //url:'http://111.172.238.250:8888'
            nick: 'wuhan'
        });
 
 
 
        // we have to wait until it's ready
        webrtc.on('readyToCall', function () {
            // you can name it anything
            webrtc.joinRoom('room1');
 
            // Send a chat message
            $('#send').click(function () {
                var msg = $('#text').val();
                webrtc.sendToAll('chat', { message: msg, nick: webrtc.config.nick });
                $('#messages').append('<br>You:<br>' + msg + '\n');
                $('#text').val('');
            });
        });
 
        //For Text Chat ------------------------------------------------------------------
        // Await messages from others
        webrtc.connection.on('message', function (data) {
            if (data.type === 'chat') {
                console.log('chat received', data);
                $('#messages').append('<br>' + data.payload.nick + ':<br>' + data.payload.message+ '\n');
            }
        });
        
    </script>
    <style>
        #remoteVideos video {
            height: 150px;
        }
 
        #localVideo {
            height: 150px;
        }
    </style>
</head>
<body>
    <textarea id="messages" rows="5" cols="20"></textarea><br />
    <input id="text" type="text" />
    <input id="send" type="button" value="send" /><br />
    <video id="localVideo"></video>
    <div id="remoteVideos"></div>
</body>
</html>

  修改里面的nick:‘wuhan’為自己的名字,用firefox或chrome打開,即可開始測試。

2 效果

 

界面簡陋了點,上面是收發消息,下面是本地和遠程的視頻圖:

3 原理

先簡單介紹下SimpleWebRTC,它是WebRTC的一個封裝類庫。

WebRTC的目的是為了簡化基於瀏覽器的實時數據通信的開發工作量,但實際應用編程還是有點復雜,尤其調用RTCPeerConnection必須對怎樣建立連接、交換信令的流程和細節有較深入的理解。因此有高人為我們開發了WebRTC封裝庫,將WebRTC的調用細節封裝起來,包裝成更簡單的API,使開發應用程序更簡單。封裝庫的還有一個目的是為了屏蔽不同瀏覽器之間的差異,比如上面說的API名稱的差異。當然,這些庫都是開源的,能夠依據自己的須要又一次改動。

眼下網上找到的有兩種WebRTC封裝庫,一個是webrtc.io,網址是https://github.com/webRTC/webRTC.io,上面有具體說明和用法,有非常多demo使用它;還有一個是SimpleWebRTC,網址是https://github.com/HenrikJoreteg/SimpleWebRTC,貌似比webrtc.io用起來更簡單。

 

3.1 視頻聊天

這是官方第一個demo,三步創建視頻聊天:

3.1.1 html頁面

<!DOCTYPE html>
<html>
    <head>
        <script src="//simplewebrtc.com/latest.js"></script> 
    </head>
    <body>
        <video height="300" id="localVideo"></video>
        <div id="remotesVideos"></div>
    </body>
</html>

  

3.1.2 創建web RTC對象

var webrtc = new SimpleWebRTC({
  // the id/element dom element that will hold "our" video
  localVideoEl: 'localVideo',
  // the id/element dom element that will hold remote videos
  remoteVideosEl: 'remotesVideos',
  // immediately ask for camera access
  autoRequestMedia: true
});

  

3.1.3 進入房間

// we have to wait until it's ready
webrtc.on('readyToCall', function () {
  // you can name it anything
  webrtc.joinRoom('wuhan');
});

  

3.2 文本聊天

這個是最基本的功能,但官方文檔里居然沒有介紹,很奇怪。

3.2.1 html內容

<textarea id="messages" rows="5" cols="20"></textarea><br />
<input id="text" type="text" />
<input id="send" type="button" value="send" /><br />

  

3.2.2 發消息

// Send a chat message
$('#send').click(function () {
   var msg = $('#text').val();
   webrtc.sendToAll('chat', { message: msg, nick: webrtc.config.nick });
   $('#messages').append('<br>You:<br>' + msg + '\n');
   $('#text').val('');
});

  

3.3.3 收消息

// Await messages from others
  webrtc.connection.on('message', function (data) {
      if (data.type === 'chat') {
          console.log('chat received', data);
          $('#messages').append('<br>' + data.payload.nick + ':<br>' + data.payload.message+ '\n');
      }
  });

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM