管理房间与频道
将 WebSocket 客户端组织到房间和频道中,让消息只发送给相关群组,这是聊天和协作应用的基础。
管理房间与频道 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。
本课时的部分内容尚未翻译,以英文显示。
Why Rooms
Broadcasting to everyone does not scale for multi-topic apps. Rooms (or channels) let you group clients so a message only reaches members of one group, like a single chat room.
Modeling Rooms
A simple model maps a room name to a set of client connections.
const rooms = new Map(); // roomName -> Set<ws>Joining a Room
When a client asks to join, add its connection to that room set, creating the set on first use.
function join(room, ws) {
if (!rooms.has(room)) rooms.set(room, new Set());
rooms.get(room).add(ws);
}Leaving a Room
Remove the connection on leave, and clean up empty rooms to avoid leaks.
function leave(room, ws) {
const set = rooms.get(room);
if (!set) return;
set.delete(ws);
if (set.size === 0) rooms.delete(room);
}A Join Message Protocol
Clients signal intent with structured messages. Parse the type and route accordingly.
ws.on('message', (raw) => {
const msg = JSON.parse(raw);
if (msg.type === 'join') join(msg.room, ws);
});Broadcasting to a Room
To send to a room, iterate only that room set, skipping closed sockets.
function toRoom(room, payload) {
const set = rooms.get(room);
if (!set) return;
for (const client of set) {
if (client.readyState === 1) client.send(payload);
}
}Tracking a Client\u2019s Rooms
Store room membership on the connection so cleanup on disconnect is easy.
ws.rooms = new Set();Cleaning Up on Disconnect
When a socket closes, remove it from every room it joined.
ws.on('close', () => {
for (const room of ws.rooms) leave(room, ws);
});Channels vs Rooms
Terms vary. Often a channel is a named topic clients subscribe to, while a room is a private group. Mechanically both are just keyed sets of subscribers.
Presence Awareness
You can derive presence from room membership: the size of a room set is the number of online members, and join/leave events can notify others.
toRoom(room, JSON.stringify({ type: 'presence', count: rooms.get(room).size }));Best Practices
Keep room management robust:
- Always clean up on disconnect
- Skip sockets not in OPEN state
- Validate room names from clients
- Remove empty rooms to free memory
Quick Check
Test your rooms knowledge.
Recap
You added rooms to your WebSocket server:
- Map room names to sets of connections
- Handle join/leave via structured messages
- Broadcast only to a room\u2019s members
- Clean up on disconnect and derive presence
This is the backbone of chat and collaboration features.
常见问题解答
「管理房间与频道」课时是免费的吗?
是的 — 「管理房间与频道」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。
「管理房间与频道」这节课中我会学到什么?
将 WebSocket 客户端组织到房间和频道中,让消息只发送给相关群组,这是聊天和协作应用的基础。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 WebSockets & Realtime Systems Programming 需要有经验吗?
无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「管理房间与频道」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?
能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。