LePhenix47 / Lahouiti_Younes_P13_21062024

This repo contains the code for the a Proof of Concept (PoC) for the "Your car your way" app for the support page using WebSockets and WebRTC
MIT License
1 stars 0 forks source link

WebRTC demo code #1

Closed LePhenix47 closed 3 weeks ago

LePhenix47 commented 1 month ago

Videos for WebRTC:

Documentation:

LePhenix47 commented 1 month ago

Sender demo code:

const iceStunServers = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'stun:stun1.l.google.com:19302' },
    { urls: 'stun:stun2.l.google.com:19302' },
  ],
  iceCandidatePoolSize: 1,
};

const localConnection = new RTCPeerConnection(iceStunServers)

const dataChannel = localConnection.createDataChannel("test")

dataChannel.onmessage = e => { console.log("New data channel msg:", e.data) }

dataChannel.onopen = e => { console.log("Connection opened:") }

localConnection.onicecandidate = e => {
  console.log("SDP:", JSON.stringify(localConnection.localDescription))
}

const offer = await localConnection.createOffer()
await localConnection.setLocalDescription(offer)

Once the receiver gives their SDP:

const answerSdp = { "type": "offer", "sdp": "v=0..." } // Copy the SDP from the receiver
localConnection.setRemoteDescription(answerSdp)
LePhenix47 commented 1 month ago

Receiver demo code:

const iceStunServers = {
  iceServers: [
    { urls: 'stun:stun.l.google.com:19302' },
    { urls: 'stun:stun1.l.google.com:19302' },
    { urls: 'stun:stun2.l.google.com:19302' },
  ],
  iceCandidatePoolSize: 1,
};

const remoteConnection = new RTCPeerConnection(iceStunServers)

remoteConnection.onicecandidate = e => {
  console.log("SDP:", JSON.stringify(remoteConnection.localDescription))
}

let dataChannel = null
remoteConnection.ondatachannel = e => {
  console.log("Data dataChannel event", e)
  dataChannel = e.channel

  dataChannel.onmessage = (e) => {
    console.log("new message", e.data)
  }

  dataChannel.onopen = (e) => {
    console.log("Connected to other peer LETS GOOOO!!!!", e)
  }
}

Once the sender sent their SDP:

const offerSdp = { "type": "offer", "sdp": "v=0..." } // Copy the SDP from the sender
await remoteConnection.setRemoteDescription(offerSdp)

const answer = await remoteConnection.createAnswer()
await remoteConnection.setLocalDescription(answer)
console.log("Answer created")
LePhenix47 commented 1 month ago

Now to send messages we can send messages to each other:

dataChannel.send("Yo, what's going on ?")
LePhenix47 commented 1 month ago

PS: We're using the Data Channel because we didn't set up any WebSocket, normally this should be handled via WebSocket

LePhenix47 commented 1 month ago

How to toggle webcam:

function toggleWebcam() {
    const videoTrack = userStream.getTracks().find(track => track.kind === 'video');
    videoTrack.enabled = !videoTrack.enabled;
}