Created
October 10, 2019 05:25
-
-
Save SumindaD/e3e07e04516024a7da2526a20bcbbf50 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function createRTCPeerConnection(){ | |
connection = new RTCPeerConnection(configuration); | |
// Add both video and audio tracks to the connection | |
for (const track of localStream.getTracks()) { | |
log("Sending Stream.") | |
existingTracks.push(connection.addTrack(track, localStream)); | |
} | |
// This event handles displaying remote video and audio feed from the other peer | |
connection.ontrack = event => { | |
log("Recieved Stream."); | |
document.getElementById("remoteVideo").srcObject = event.streams[0]; | |
} | |
// This event handles the received data channel from the other peer | |
connection.ondatachannel = function (event) { | |
log("Recieved a DataChannel.") | |
channel = event.channel; | |
setChannelEvents(channel); | |
document.getElementById("sendMessageButton").disabled = false; | |
}; | |
// This event sends the ice candidates generated from Stun or Turn server to the Receiver over web socket | |
connection.onicecandidate = event => { | |
if (event.candidate) { | |
log("Sending Ice Candidate - " + event.candidate.candidate); | |
socket.send(JSON.stringify( | |
{ | |
action: 'onMessage', | |
type: 'candidate', | |
data: event.candidate, | |
id: clientId | |
} | |
)); | |
} | |
} | |
// This event logs messages and handles button state according to WebRTC connection state changes | |
connection.onconnectionstatechange = function(event) { | |
switch(connection.connectionState) { | |
case "connected": | |
log("Web RTC Peer Connection Connected."); | |
document.getElementById("answerButton").disabled = true; | |
document.getElementById("sendOfferButton").disabled = true; | |
document.getElementById("hangUpButton").disabled = false; | |
document.getElementById("sendMessageButton").disabled = false; | |
break; | |
case "disconnected": | |
log("Web RTC Peer Connection Disconnected. Please reload the page to reconnect."); | |
disableAllButtons(); | |
break; | |
case "failed": | |
log("Web RTC Peer Connection Failed. Please reload the page to reconnect."); | |
console.log(event); | |
disableAllButtons(); | |
break; | |
case "closed": | |
log("Web RTC Peer Connection Failed. Please reload the page to reconnect."); | |
disableAllButtons(); | |
break; | |
default: | |
break; | |
} | |
} | |
log("Web RTC Peer Connection Created."); | |
document.getElementById("sendOfferButton").disabled = false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment