Renegocjacja i stan połączenia
Naucz się, jak połączenia WebRTC peer-to-peer zmieniają się w czasie: monitoruj stan połączenia, obsługuj restarty ICE i renegocjuj SDP, gdy zmienią się warunki mediów lub sieci.
Renegocjacja i stan połączenia to bezpłatna lekcja Real-Time Streaming Systems (WebRTC + Live Data) na CoddyKit. To lekcja 4 z 4. Możesz przeczytać całą lekcję poniżej za darmo — a potem ćwiczyć ją interaktywnie w przeglądarce z wbudowanym edytorem kodu i tutorem AI dostępnym 24/7. To część ścieżki edukacyjnej Real-Time Streaming Systems (WebRTC + Live Data), a Twój postęp synchronizuje się między webem a aplikacją CoddyKit. Kurs Real-Time Streaming Systems (WebRTC + Live Data) zawiera 4 lekcji w sumie.
Części tej lekcji nie zostały jeszcze przetłumaczone i są wyświetlane po angielsku.
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.
Często zadawane pytania
Czy lekcja „Renegocjacja i stan połączenia” jest bezpłatna?
Tak — pełny tekst „Renegocjacja i stan połączenia” jest dostępny za darmo tutaj w sieci. Aby ćwiczyć ją interaktywnie (wbudowany edytor kodu i tutor AI dostępny 24/7) i odblokować resztę kursu Real-Time Streaming Systems (WebRTC + Live Data), przejdź na CoddyKit PRO. Kurs Real-Time Streaming Systems (WebRTC + Live Data) zawiera 4 lekcji w sumie.
Co nauczysz się w „Renegocjacja i stan połączenia”?
Naucz się, jak połączenia WebRTC peer-to-peer zmieniają się w czasie: monitoruj stan połączenia, obsługuj restarty ICE i renegocjuj SDP, gdy zmienią się warunki mediów lub sieci. Ćwiczysz Real-Time Streaming Systems (WebRTC + Live Data) z praktycznym kodem, który uruchamiasz bezpośrednio w przeglądarce, a tutor AI dostępny 24/7 odpowiada na Twoje pytania podczas pracy nad lekcją.
Czy potrzebuję doświadczenia, aby zacząć Real-Time Streaming Systems (WebRTC + Live Data)?
Nie wymagamy żadnego doświadczenia. Real-Time Streaming Systems (WebRTC + Live Data) w CoddyKit jest strukturyzowany dla początkujących i zaawansowanych użytkowników, więc możesz zacząć tutaj lub od początku i uczyć się w swoim tempie. To lekcja 4 z 4.
Ile czasu zajmuje lekcja „Renegocjacja i stan połączenia”?
Większość lekcji CoddyKit trwa około 5–10 minut. Każda lekcja to mały, interaktywny krok, dzięki czemu robisz systematyczne postępy i zawsze wracasz dokładnie do tego samego miejsca — na webie i w aplikacji.
Czy mogę pisać i uruchamiać kod w tej lekcji Real-Time Streaming Systems (WebRTC + Live Data)?
Tak. Każda lekcja Real-Time Streaming Systems (WebRTC + Live Data) zawiera wbudowany edytor kodu, więc piszesz i uruchamiasz prawdziwy kod bezpośrednio w przeglądarce i od razu otrzymujesz sprzężenie zwrotne od AI — bez konfiguracji na komputerze.
Wszystkie lekcje w tym kursie
- Rola serwerów sygnalizacyjnych
- SDP: Session Description Protocol
- Kandydaci ICE i nawiązywanie połączenia
- Renegocjacja i stan połączenia