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

实时共享应用状态

探索利用实时数据同步应用状态的技术,从而实现协作功能和共享体验。

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

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

What is Shared State?

Imagine multiple people working on the same document or playing the same game. They need to see the same information and changes in real-time. This common, synchronized information is called shared application state.

It's the data that reflects the current status of an application, accessible and modifiable by all connected participants.

Why Share State Live?

Sharing state live is crucial for creating truly collaborative and interactive experiences. Think about:

  • Collaborative Editing: Multiple users typing in a document simultaneously.
  • Multi-user Drawing: Everyone sees lines appear as they are drawn.
  • Online Games: Synchronizing player positions, scores, and game events.
  • Shared Whiteboards: Real-time updates to drawings and notes.

It makes applications feel responsive and connected.

Data Channels for State Sync

In WebRTC, RTCDataChannel is your go-to tool for sharing application state. Unlike media streams (audio/video), data channels are designed for sending arbitrary data, from text messages to binary files.

They provide a fast, direct, and secure peer-to-peer connection, making them ideal for small, frequent state updates without latency.

Representing Application State

Before sending, you need to decide how to structure your application state. A common and flexible way is using plain JavaScript objects or JSON (JavaScript Object Notation).

This allows you to easily store different types of data like text, numbers, and nested objects, ready for serialization.

Try running this example of a simple state object:

let sharedAppState = {
  documentTitle: "My Collaborative Doc",
  cursorPosition: { x: 0, y: 0 },
  selectedTool: "pen",
  version: 1
};

console.log("Initial state:");
console.log(sharedAppState);

Sending State Updates

When a user makes a change, you update your local state. Then, you need to send this change to other peers. Data Channels expect string or binary data.

We use JSON.stringify() to convert our JavaScript object into a JSON string before sending it via dataChannel.send() (conceptually).

Here's how to prepare an update:

let localState = { counter: 5 };

// Simulate a data channel send function
function sendData(data) {
  console.log("Sending data:", data);
}

// A change occurs
localState.counter++; // counter is now 6

// Create an object for the update
let update = { counter: localState.counter };

// Convert the update to a JSON string
let jsonUpdate = JSON.stringify(update);

sendData(jsonUpdate);
// Expected output: Sending data: {"counter":6}

Receiving & Applying Updates

When another peer sends an update, your dataChannel.onmessage event handler will receive it. The received data will be a string (or ArrayBuffer).

You then use JSON.parse() to convert the JSON string back into a JavaScript object. Finally, you apply these changes to your local application state, often using Object.assign() for merging.

See how to process a received update:

let appState = { message: "Hello", count: 0 };

// Simulate receiving a message from a data channel
let receivedMessage = '{"message": "World", "count": 1}';

// When a message is received:
function handleMessage(eventData) {
  let update = JSON.parse(eventData);
  // Merge the received update into the current state
  Object.assign(appState, update);
  console.log("State after update:");
  console.log(appState);
}

handMessage(receivedMessage);
// Expected output:
// State after update:
// { message: 'World', count: 1 }

Full State vs. Delta Updates

When sharing state, you can either send the entire application state every time a change occurs, or just send the "diff" (delta update), which is only the part of the state that changed.

For large states or frequent small changes, sending only diffs is more efficient as it uses less bandwidth. However, sending the full state can be simpler to implement and more robust against missed messages in some scenarios.

Handling State Conflicts

What happens if two users try to change the same part of the state at the exact same time? This is a state conflict.

Simple solutions include "last write wins" (the last received update overrides previous ones). More advanced systems use techniques like CRDTs (Conflict-free Replicated Data Types), which are data structures designed to merge changes from different sources automatically without conflicts.

Shared Counter Example Flow

Let's imagine a simple shared counter application. Each peer has a button to increment the counter.

  1. Initial State: Both peers start with counter: 0.
  2. User Action: Peer A clicks "Increment". Local counter becomes 1.
  3. Send Update: Peer A sends {"counter": 1} via Data Channel.
  4. Receive Update: Peer B receives {"counter": 1}, parses it, and updates its local counter to 1.
  5. Synchronization: Both peers now show counter: 1.

This simple flow demonstrates the core of live state synchronization.

Check Your Understanding

When building a collaborative application that uses WebRTC Data Channels to synchronize application state, which of the following are key considerations?

Recap: Shared Live State

In this lesson, you learned about the importance of sharing application state live for collaborative features. We covered how RTCDataChannel is ideal for this, and the process of representing, sending, and receiving state updates using JSON serialization.

You also explored challenges like state conflicts and strategies for choosing between full state and delta updates. These techniques are fundamental for building responsive, multi-user applications.

常见问题解答

「实时共享应用状态」课时是免费的吗?

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

「实时共享应用状态」这节课中我会学到什么?

探索利用实时数据同步应用状态的技术,从而实现协作功能和共享体验。 你通过在浏览器中直接运行的动手代码来练习 Real-Time Streaming Systems (WebRTC + Live Data),全天候 AI 导师会在你学习这节课的过程中回答你的问题。

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

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

「实时共享应用状态」课时需要多长时间?

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

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

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

此课程中的所有课时

  1. 同步 WebRTC 元数据
  2. 通过数据通道实现实时聊天
  3. 实时共享应用状态
  4. 通过 WebRTC 数据通道传输文件
← 返回 Real-Time Streaming Systems (WebRTC + Live Data)