Chat room using WebRTC

Posted By : Asheesh Bhuria | 30-Apr-2019

This blog gives a brief overview of how WebRTC connection between two peers can be established, as well as how to create a chat room by maintaining such multiple peers to peer connection. The communication between the signaling server (backend) and the frontend is maintained by WebSockets.

 

Pre-requisites - A basic understanding of WebRTC connection

 

Let’s dive into the coding section,

 

Getting the permissions from the browser for accessing Webcam and Microphone. Creating a Video element and appending it to the HTML body. And attach client’s media stream in the Video element.

navigator.mediaDevices.getUserMedia({ 'audio': true, 'video': true })
.then(gumStream => {
         local_media_stream = gumStream;
		// Creating video element
         var local_video_setup =  USE_VIDEO ?   document.createElement("video") : document.createElement("audio")
         
         local_video_setup.muted = true
         local_video_setup.autoplay = true
         local_video_setup.controls = true
         $('#videoContainer').append(local_video_setup);
		// Attaching client’s media stream to the newly created html element 
        local_video_setup.srcObject = gumStream);
}).catch(err => {
         console.log('Error in setting local video: ' + err)
})

The server keeps a record of every client - Whenever a client joins the chatroom, a socket connection is initiated between the client and the server. The server keeps the record of each client using an object which stores socket id as key and socket object as the value

As soon as the client joins the chat room, the server shares the details of clients with one another.                     

When a client receives information about a new peer:-

  1. Create a RTC connection for the new peer

  1.  
  1. ICE_SERVERS = [{
         urls: URL
       }]
    let peer_connection = new RTCPeerConnection({ iceServers: ICE_SERVERS });
    

    ICE_SERVERS contains information about STUN and TURN servers.

  2. Create peer connection - nice candidate and on track handlers

  1.  
  1. peer_connection.onicecandidate = function (event) {
        	if (event.candidate) {
            	// Share ice candidate information with the remote peer
             }
    }
    peer_connection.ontrack = function (event) {
    // Create a new video element using previously defined method
    //Attaching media stream 
    videoElement.srcObject = event.Streams[0]     
    }
    
  2. Create offers,  if created relay session description to peer via server

  1.  
  1. peer_connection.createOffer().then(local_description => {
               return peer_connection.setLocalDescription(local_description)
             }).then(function () {
               // send Session Description to the peer
             }).catch(error => {
               console.log( error);
             })
    

 

When the client receives a session description from one of its peers, it sets the remote description and then creates an answer if SDP type is an offer

peer.setRemoteDescription(desc)
         .then(function () {
           if (remote_description.type == 'offer') {
             return peer.createAnswer().then(answer => {
               peer.setLocalDescription(answer)
                 .then(function () {
                   // Send the answer to the remote peer by using the signaling server
                 })
                 .catch(error => {
                   // handle error
                 })
             }).catch(err => {
               // handle error
             })
           }
         })

 

When a remote peer receives Ice Candidate’s information it adds a candidate to the peer connection--

let ice_candidate_object = new RTCIceCandidate(ice_candidate)
peer.addIceCandidate(ice_candidate_object)

Ice_candidates  contains the Ice candidate information


 

The above methodology gave us the desired results. We were able to test it successfully on the Chrome browser with six users at a time.

 

 

 

 

 

 

About Author

Author Image
Asheesh Bhuria

Asheesh Bhuria is a software engineer. With his knowledge in new technologies he excels in MEAN Stack development.

Request for Proposal

Name is required

Comment is required

Sending message..