Transmitting a video stream from Client A to Client B in WebRTC involves multiple steps. The following provides an overview and detailed explanation of each step:
1. Get Media Input
First, Client A uses the WebRTC API getUserMedia to obtain local video and audio streams. This API requests permission from the user to access the computer's camera and microphone.
javascriptnavigator.mediaDevices.getUserMedia({ video: true, audio: true }) .then(function(stream) { // Can be used for preview or streaming localVideo.srcObject = stream; }) .catch(function(error) { console.error('Failed to get media:', error); });
2. Create RTCPeerConnection
Next, Client A and Client B each create an RTCPeerConnection object. This object handles the encoding and network transmission of the video stream.
javascriptconst peerConnection = new RTCPeerConnection();
3. Add Local Stream to Connection
Client A adds the obtained video stream to its RTCPeerConnection instance.
javascriptpeerConnection.addStream(stream);
4. Set ICE Handling
To establish a connection between the two clients, they collect and exchange ICE candidates. WebRTC uses the ICE framework to handle NAT traversal and firewalls.
javascriptpeerConnection.onicecandidate = function(event) { if (event.candidate) { // In a real scenario, this would use the signaling service to send candidates to the other client sendToServer('new-ice-candidate', event.candidate); } };
5. Create and Exchange Offer and Answer
Client A creates an offer and sends it to Client B via the server. Upon receiving it, Client B creates an answer and sends it back to Client A.
javascript// Client A creates Offer peerConnection.createOffer() .then(offer => { return peerConnection.setLocalDescription(offer); }) .then(() => { // Sent via signaling to Client B sendToServer('offer', peerConnection.localDescription); }); // Client B sets Remote Description and creates Answer peerConnection.setRemoteDescription(offer) .then(() => { return peerConnection.createAnswer(); }) .then(answer => { return peerConnection.setLocalDescription(answer); }) .then(() => { // Sent via signaling back to Client A sendToServer('answer', peerConnection.localDescription); });
6. Establish Connection and Stream Transmission
Once Client A and Client B successfully exchange all necessary information (offer, answer, ICE candidates), their RTCPeerConnection objects attempt to establish a connection. If successful, the video stream begins transmitting from Client A to Client B.
The signaling server acts as a relay for communication but does not handle the media stream itself. This is a typical WebRTC use case enabling real-time video and audio communication.