Renegociación y estado de la conexión
Aprenda cómo cambian las conexiones entre pares de WebRTC con el tiempo: supervise el estado de la conexión, gestione reinicios de ICE y renegocie SDP cuando cambien los medios o las condiciones de red.
Renegociación y estado de la conexión es una lección gratuita de Real-Time Streaming Systems (WebRTC + Live Data) en CoddyKit. Esta es la lección 4 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Real-Time Streaming Systems (WebRTC + Live Data), y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Real-Time Streaming Systems (WebRTC + Live Data) incluye 4 lecciones en total.
Partes de esta lección aún no han sido traducidas y se muestran en inglés.
Connections Are Not Static
You have set up signaling, SDP, and ICE to create a connection. But a real session evolves: a user adds screen share, switches networks, or recovers from a drop. Handling these changes is called renegotiation and state management.
The Connection State Machine
An RTCPeerConnection reports its health through connectionState, moving through values like new, connecting, connected, disconnected, failed, and closed.
pc.onconnectionstatechange = () => {
console.log('state:', pc.connectionState);
};Reacting to State
Use the state to drive UI and recovery logic, such as showing a reconnecting spinner or tearing down a dead connection.
pc.onconnectionstatechange = () => {
switch (pc.connectionState) {
case 'connected': showCall(); break;
case 'disconnected': showReconnecting(); break;
case 'failed': restartConnection(); break;
case 'closed': cleanup(); break;
}
};ICE Connection State
Separately, iceConnectionState tracks the connectivity checks. A transition to disconnected may be temporary, while failed usually means connectivity must be re-established.
pc.oniceconnectionstatechange = () => {
if (pc.iceConnectionState === 'failed') {
pc.restartIce();
}
};What Is an ICE Restart?
When a network path dies (for example, switching from Wi-Fi to cellular), the existing candidates no longer work. An ICE restart gathers fresh candidates and finds a new path without recreating the whole connection.
When Renegotiation Is Needed
Any change to the set of media tracks or transceivers requires a new offer/answer exchange. The browser tells you via the negotiationneeded event.
pc.onnegotiationneeded = async () => {
const offer = await pc.createOffer();
await pc.setLocalDescription(offer);
signaling.send({ type: 'offer', sdp: offer });
};Adding a Track Mid-Call
Adding a screen-share track during a call triggers negotiationneeded, prompting a fresh SDP exchange that updates the remote peer.
async function startScreenShare() {
const screen = await navigator.mediaDevices.getDisplayMedia();
const track = screen.getVideoTracks()[0];
pc.addTrack(track, screen); // fires negotiationneeded
}The Glare Problem
If both peers create offers at the same time, they collide. This is called glare. The fix is the perfect negotiation pattern, where one peer is polite and rolls back its offer when a collision occurs.
Perfect Negotiation Sketch
A polite peer rolls back on collision; the impolite peer ignores the incoming offer. This guarantees exactly one negotiation succeeds.
const offerCollision = (msg.type === 'offer') &&
(makingOffer || pc.signalingState !== 'stable');
ignoreOffer = !polite && offerCollision;
if (ignoreOffer) return;
if (offerCollision) await pc.setLocalDescription({ type: 'rollback' });Closing Cleanly
When a call ends, stop tracks and close the connection to free resources and release the camera and microphone.
function hangUp() {
pc.getSenders().forEach(s => s.track && s.track.stop());
pc.close();
}Putting It Together
Robust WebRTC apps monitor connection state, restart ICE on path loss, renegotiate when tracks change, and handle glare with perfect negotiation. These behaviors turn a fragile demo into a reliable product.
Quick Check
Test your understanding of renegotiation.
Recap
You learned about connection state and renegotiation:
connectionStateandiceConnectionStatereport health- ICE restart recovers from network path changes
negotiationneededtriggers a fresh SDP exchange- Perfect negotiation resolves glare; clean shutdown frees devices
These skills keep peer connections resilient over time.
Preguntas frecuentes
¿La lección «Renegociación y estado de la conexión» es gratis?
Sí — el texto completo de «Renegociación y estado de la conexión» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Real-Time Streaming Systems (WebRTC + Live Data), actualiza a CoddyKit PRO. El curso de Real-Time Streaming Systems (WebRTC + Live Data) incluye 4 lecciones en total.
¿Qué aprenderé en «Renegociación y estado de la conexión»?
Aprenda cómo cambian las conexiones entre pares de WebRTC con el tiempo: supervise el estado de la conexión, gestione reinicios de ICE y renegocie SDP cuando cambien los medios o las condiciones de r… Practicas Real-Time Streaming Systems (WebRTC + Live Data) con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.
¿Necesito experiencia previa para empezar Real-Time Streaming Systems (WebRTC + Live Data)?
No se requiere experiencia previa. Real-Time Streaming Systems (WebRTC + Live Data) en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 4 de 4.
¿Cuánto tiempo toma la lección «Renegociación y estado de la conexión»?
La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.
¿Puedo escribir y ejecutar código en esta lección de Real-Time Streaming Systems (WebRTC + Live Data)?
Sí. Cada lección de Real-Time Streaming Systems (WebRTC + Live Data) incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.
Todas las lecciones de este curso
- El papel de los servidores de signaling
- SDP: protocolo de descripción de sesión
- Candidatos ICE y conectividad
- Renegociación y estado de la conexión