Renegociação e Estado da Conexão
Aprenda como as conexões entre pares do WebRTC mudam ao longo do tempo: monitore o estado da conexão, trate reinicializações de ICE e renegocie SDP quando as condições de mídia ou rede mudarem.
Renegociação e Estado da Conexão é uma aula grátis de Real-Time Streaming Systems (WebRTC + Live Data) no CoddyKit. Esta é a aula 4 de 4. Você pode ler a aula completa abaixo gratuitamente — depois pratica ao vivo no navegador com um editor de código integrado e um tutor de IA 24/7. Faz parte do caminho de aprendizado de Real-Time Streaming Systems (WebRTC + Live Data), e seu progresso é sincronizado entre a web e o app CoddyKit. O curso de Real-Time Streaming Systems (WebRTC + Live Data) inclui 4 aulas no total.
Partes desta aula ainda não foram traduzidas e aparecem em 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.
Perguntas Frequentes
A aula “Renegociação e Estado da Conexão” é grátis?
Sim — o texto completo de “Renegociação e Estado da Conexão” é grátis para ler aqui na web. Para praticá-la interativamente (um editor de código integrado e um tutor de IA 24/7) e desbloquear o restante do curso de Real-Time Streaming Systems (WebRTC + Live Data), atualize para CoddyKit PRO. O curso de Real-Time Streaming Systems (WebRTC + Live Data) inclui 4 aulas no total.
O que vou aprender em “Renegociação e Estado da Conexão”?
Aprenda como as conexões entre pares do WebRTC mudam ao longo do tempo: monitore o estado da conexão, trate reinicializações de ICE e renegocie SDP quando as condições de mídia ou rede mudarem. Você pratica Real-Time Streaming Systems (WebRTC + Live Data) com código prático que executa diretamente no navegador, e um tutor de IA 24/7 responde suas dúvidas enquanto trabalha na aula.
Preciso ter experiência prévia para começar Real-Time Streaming Systems (WebRTC + Live Data)?
Nenhuma experiência prévia é necessária. Real-Time Streaming Systems (WebRTC + Live Data) no CoddyKit é estruturado para alunos iniciantes até avançados, então você pode começar aqui ou desde o início e aprender no seu ritmo. Esta é a aula 4 de 4.
Quanto tempo leva a aula “Renegociação e Estado da Conexão”?
A maioria das aulas CoddyKit leva cerca de 5–10 minutos. Cada uma é compacta e interativa, então você faz progresso constante e retoma exatamente de onde parou entre web e app.
Posso escrever e executar código nesta aula de Real-Time Streaming Systems (WebRTC + Live Data)?
Sim. Cada aula de Real-Time Streaming Systems (WebRTC + Live Data) inclui um editor de código integrado, então você escreve e executa código real direto no navegador e recebe feedback de IA instantaneamente — nenhuma configuração local necessária.
Todas as aulas deste curso
- O papel dos servidores de sinalização
- SDP: protocolo de descrição de sessão
- Candidatos ICE e conectividade
- Renegociação e Estado da Conexão