0Pricing
WebSockets & Realtime Systems Programming · 课时

实时聊天与游戏服务器

探索构建高性能实时聊天平台和多人游戏后端时面临的挑战及解决方案。

实时聊天与游戏服务器 是 CoddyKit 上的免费 WebSockets & Realtime Systems Programming 课时。 这是第 2 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 WebSockets & Realtime Systems Programming 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

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

Realtime Demands of Chat & Games

Live chat applications and multiplayer games are the epitome of realtime communication. They demand instant updates, low latency, and efficient data exchange between many users.

Traditional HTTP, with its request-response model, simply isn't suited for this constant, bidirectional flow of information. This is where WebSockets truly shine.

Tackling Latency & Throughput

One of the biggest challenges is ensuring low latency, meaning messages and game actions arrive almost instantly. High throughput is also crucial to handle many messages per second.

  • Chat: Messages must appear immediately.
  • Games: Player movements, attacks, and scores need to sync without noticeable delay.

WebSockets provide a persistent connection, minimizing overhead compared to repeated HTTP requests, which helps achieve these goals.

Managing Dynamic State

In both chat and games, the server needs to manage dynamic state. This includes:

  • Which users are online.
  • Who is in which chat room or game session.
  • Player positions, health, and scores in a game.
  • Recent chat history.

This state often resides in memory for speed but might be persisted to a database for recovery or long-term history.

Structuring with Rooms & Channels

To manage communication for many users, we often use rooms or channels. Instead of sending every message to every user, messages are routed to specific groups.

  • A chat room for a specific topic.
  • A game lobby or an active game instance.

This approach significantly reduces network traffic and server load by sending data only where it's needed.

Server: Joining a Chat Room

This Node.js example sets up a WebSocket server. Clients can send a joinRoom message to become part of a specific chat room. The server uses a Map to keep track of active rooms and their connected clients.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const rooms = new Map(); // Map: roomName -> Set<WebSocket>

wss.on('connection', ws => {
  console.log('Client connected.');

  ws.on('message', message => {
    const msg = JSON.parse(message);
    if (msg.type === 'joinRoom') {
      const roomName = msg.room;
      if (!rooms.has(roomName)) {
        rooms.set(roomName, new Set());
      }
      rooms.get(roomName).add(ws);
      ws.currentRoom = roomName; // Store room on connection
      ws.send(`You joined: ${roomName}`);
      console.log(`Client joined room '${roomName}'`);
    }
  });

  ws.on('close', () => {
    if (ws.currentRoom) {
      rooms.get(ws.currentRoom).delete(ws);
      if (rooms.get(ws.currentRoom).size === 0) {
        rooms.delete(ws.currentRoom);
      }
    }
    console.log('Client disconnected.');
  });

  ws.send('Send {\"type\": \"joinRoom\", \"room\": \"lobby\"}');
});

console.log('WebSocket server running on port 8080.');

Broadcasting & Targeted Delivery

Once clients are in rooms, the server needs to efficiently send messages:

  • Broadcast: To all clients in a specific room (e.g., a public chat message).
  • Unicast: To a single, specific client (e.g., a private message or a game command for one player).

This targeted delivery is key to keeping the application responsive and preventing unnecessary data transfer.

Server: Broadcasting Chat Messages

Building on the room concept, this code shows how the server can receive a chat message and broadcast it to all other clients in the same room. Notice how it iterates through the Set of clients for the current room.

const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 8080 });

const rooms = new Map(); // Map: roomName -> Set<WebSocket>

wss.on('connection', ws => {
  ws.on('message', message => {
    const msg = JSON.parse(message);
    if (msg.type === 'joinRoom') {
      const roomName = msg.room;
      if (!rooms.has(roomName)) {
        rooms.set(roomName, new Set());
      }
      rooms.get(roomName).add(ws);
      ws.currentRoom = roomName;
      ws.send(`You joined: ${roomName}`);
    } else if (msg.type === 'chat' && ws.currentRoom) {
      const roomClients = rooms.get(ws.currentRoom);
      roomClients.forEach(client => {
        if (client.readyState === WebSocket.OPEN) {
          client.send(`[${ws.currentRoom}] User says: ${msg.text}`);
        }
      });
    }
  });

  ws.on('close', () => {
    if (ws.currentRoom) {
      rooms.get(ws.currentRoom).delete(ws);
      if (rooms.get(ws.currentRoom).size === 0) {
        rooms.delete(ws.currentRoom);
      }
    }
  });

  ws.send('Send {\"type\": \"joinRoom\", \"room\": \"lobby\"} then {\"type\": \"chat\", \"text\": \"Hello!\"}');
});

console.log('WebSocket server running on port 8080.');

Client UI & Responsiveness

On the client-side (e.g., in a web browser), JavaScript uses the native WebSocket API to connect and handle messages. The UI is updated dynamically without page reloads.

This example shows a basic HTML structure and JavaScript to connect, join a room, and display incoming messages.

<!DOCTYPE html>
<html>
<head>
  <title>Chat Client</title>
</head>
<body>
  <div id="messages" style="border: 1px solid #ccc; height: 150px; overflow-y: scroll; padding: 5px;"></div>
  <input type="text" id="chatInput" placeholder="Type your message...">
  <button onclick="sendMessage()">Send</button>

  <script>
    const ws = new WebSocket('ws://localhost:8080');
    const messagesDiv = document.getElementById('messages');
    const chatInput = document.getElementById('chatInput');

    ws.onopen = () => {
      messagesDiv.innerHTML += '<p><em>Connected!</em></p>';
      ws.send(JSON.stringify({ type: 'joinRoom', room: 'lobby' }));
    };

    ws.onmessage = event => {
      messagesDiv.innerHTML += `<p>${event.data}</p>`;
      messagesDiv.scrollTop = messagesDiv.scrollHeight; // Auto-scroll
    };

    function sendMessage() {
      const text = chatInput.value;
      if (text.trim() !== '') {
        ws.send(JSON.stringify({ type: 'chat', text: text }));
        chatInput.value = '';
      }
    }
  </script>
</body>
</html>

Game State Synchronization

For multiplayer games, game state synchronization is critical. This involves more than just chat messages; it's about continuously updating player positions, health, scores, and game events across all connected clients.

  • Server as Authority: The server often acts as the single source of truth for the game state.
  • Game Loop: A server-side game loop frequently calculates and broadcasts state changes to clients.

Techniques like interpolation and extrapolation on the client help smooth out visual updates despite network latency.

Key Realtime Challenges

Consider the typical requirements for building a robust live chat or multiplayer game server using WebSockets. Which of the following present significant challenges?

Recap: Building Realtime Apps

In this lesson, we explored the unique challenges of building live chat and multiplayer game servers with WebSockets. We learned:

  • The critical need for low latency and high throughput.
  • Strategies for managing dynamic state for users, rooms, and game entities.
  • The importance of room-based messaging for efficient communication.
  • How servers handle joining rooms, broadcasting messages, and how clients update their UI.
  • The concept of game state synchronization for interactive experiences.

These principles form the foundation for creating engaging and responsive realtime applications.

常见问题解答

「实时聊天与游戏服务器」课时是免费的吗?

是的 — 「实时聊天与游戏服务器」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 WebSockets & Realtime Systems Programming 课程的其余内容,请升级到 CoddyKit PRO。 WebSockets & Realtime Systems Programming 课程共包含 4 节课。

「实时聊天与游戏服务器」这节课中我会学到什么?

探索构建高性能实时聊天平台和多人游戏后端时面临的挑战及解决方案。 你通过在浏览器中直接运行的动手代码来练习 WebSockets & Realtime Systems Programming,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 WebSockets & Realtime Systems Programming 需要有经验吗?

无需任何先前经验。CoddyKit 上的 WebSockets & Realtime Systems Programming 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 2 节课,共 4 节。

「实时聊天与游戏服务器」课时需要多长时间?

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

我能在这节 WebSockets & Realtime Systems Programming 课中编写并运行代码吗?

能。每节 WebSockets & Realtime Systems Programming 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 协作编辑器与白板
  2. 实时聊天与游戏服务器
  3. 实时数据仪表板
  4. 构建实时位置跟踪系统
← 返回 WebSockets & Realtime Systems Programming