Real-Time Streaming Systems (WebRTC + Live Data) · 课时

重新协商与连接状态

学习 WebRTC 对等连接如何随时间变化:监控连接状态、处理 ICE 重启,以及在媒体或网络条件变化时重新协商 SDP。

第 4 / 4 课13 个步骤

重新协商与连接状态 是 CoddyKit 上的免费 Real-Time Streaming Systems (WebRTC + Live Data) 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 Real-Time Streaming Systems (WebRTC + Live Data) 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

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:

  • connectionState and iceConnectionState report health
  • ICE restart recovers from network path changes
  • negotiationneeded triggers a fresh SDP exchange
  • Perfect negotiation resolves glare; clean shutdown frees devices

These skills keep peer connections resilient over time.

免费开始

用 AI 导师学习 Real-Time Streaming Systems (WebRTC + Live Data) — 免费

在浏览器中编写并运行真实代码,获得全天候 AI 导师的即时帮助,并在网页或应用中继续学习。

课程
12
课程
48

常见问题解答

「重新协商与连接状态」课时是免费的吗?

是的 — 「重新协商与连接状态」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 Real-Time Streaming Systems (WebRTC + Live Data) 课程的其余内容,请升级到 CoddyKit PRO。 Real-Time Streaming Systems (WebRTC + Live Data) 课程共包含 4 节课。

「重新协商与连接状态」这节课中我会学到什么?

学习 WebRTC 对等连接如何随时间变化:监控连接状态、处理 ICE 重启,以及在媒体或网络条件变化时重新协商 SDP。 你通过在浏览器中直接运行的动手代码来练习 Real-Time Streaming Systems (WebRTC + Live Data),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 Real-Time Streaming Systems (WebRTC + Live Data) 需要有经验吗?

无需任何先前经验。CoddyKit 上的 Real-Time Streaming Systems (WebRTC + Live Data) 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。

「重新协商与连接状态」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 Real-Time Streaming Systems (WebRTC + Live Data) 课中编写并运行代码吗?

能。每节 Real-Time Streaming Systems (WebRTC + Live Data) 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 信令服务器的作用
  2. SDP:会话描述协议
  3. ICE 候选项与连接性
  4. 重新协商与连接状态
← 返回 Real-Time Streaming Systems (WebRTC + Live Data)