0Pricing
WebSockets & Realtime Systems Programming · บทเรียน

การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ

ออกแบบและสร้างระบบเผยแพร่และสมัครรับผ่าน WebSockets เพื่อกระจายข้อความตามหัวข้อ

การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ เป็นบทเรียน WebSockets & Realtime Systems Programming ฟรีบน CoddyKit นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน WebSockets & Realtime Systems Programming และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

Intro to Pub/Sub Messaging

Welcome to advanced WebSocket patterns! Today, we'll explore Publish/Subscribe (Pub/Sub) messaging, a powerful way to distribute real-time data efficiently.

Imagine a digital newspaper where you only get articles on topics you care about. That's Pub/Sub in action!

It's ideal for features like live chat rooms, social media feeds, stock tickers, or any application needing dynamic, topic-based updates.

Pub/Sub's Key Players

A Pub/Sub system involves a few core components:

  • Publishers: These are entities that send messages. They don't know who will receive the messages.
  • Subscribers: These are entities that receive messages. They express interest in specific topics.
  • Topics: These are categories or channels for messages. Subscribers 'tune into' topics they want to follow.
  • Broker: This is the central component (our WebSocket server) that receives messages from publishers and forwards them to relevant subscribers.

WebSocket Server as Broker

In our WebSocket Pub/Sub system, the WebSocket server acts as the Broker.

It will be responsible for:

  • Accepting client connections.
  • Managing a list of which clients are subscribed to which topics.
  • Receiving messages from 'publisher' clients.
  • Distributing those messages to all 'subscriber' clients for the given topic.

We'll use a Map data structure on the server to store subscriptions, mapping each topic name to a Set of connected WebSocket client objects.

Designing Message Formats

To make our Pub/Sub system work, clients and the server need a clear way to communicate. We'll use simple JSON messages.

1. Subscribe Message (Client to Server):

{ "action": "subscribe", "topic": "chat:general" }

2. Publish Message (Client to Server):

{ "action": "publish", "topic": "news", "payload": "Breaking: New feature released!" }

3. Delivered Message (Server to Client):

{ "type": "message", "topic": "chat:general", "payload": "Hello everyone!" }

Server: Basic Pub/Sub Logic

Here's a complete Node.js WebSocket server implementing basic Pub/Sub. It handles both subscribe and publish messages.

Run this code (node server.js after npm install ws) and then connect clients in your browser to test it!

const { WebSocketServer } = require('ws');
const wss = new WebSocketServer({ port: 8080 });

// Stores active subscriptions: Map<topic, Set<WebSocket>>
const subscriptions = new Map();

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

  ws.on('message', message => {
    try {
      const data = JSON.parse(message.toString());
      const { action, topic, payload } = data;

      if (action === 'subscribe' && topic) {
        if (!subscriptions.has(topic)) {
          subscriptions.set(topic, new Set());
        }
        subscriptions.get(topic).add(ws);
        ws.send(JSON.stringify({ status: 'subscribed', topic }));
        console.log(`Client subscribed to '${topic}'.`);
      } else if (action === 'publish' && topic && payload) {
        const topicSubscribers = subscriptions.get(topic);
        if (topicSubscribers) {
          topicSubscribers.forEach(subscriber => {
            if (subscriber.readyState === ws.OPEN) {
              subscriber.send(JSON.stringify({ type: 'message', topic, payload }));
            }
          });
          console.log(`Published to '${topic}': ${payload}.`);
        } else {
          ws.send(JSON.stringify({ error: `No subscribers for '${topic}'.` }));
        }
      } else {
        ws.send(JSON.stringify({ error: 'Invalid message.' }));
      }
    } catch (e) {
      console.error('Message error:', e.message);
      ws.send(JSON.stringify({ error: 'JSON parse error.' }));
    }
  });

  // Connection close and error handling in the next scene
});

console.log('Pub/Sub server running on ws://localhost:8080');

Server: Connection Lifecycle

Managing the connection lifecycle is crucial for a robust Pub/Sub server. The server must handle client disconnections gracefully.

  • The ws.on('close') event fires when a client disconnects.
  • Inside this handler, we iterate through all topics and remove the disconnected client from any subscription lists it was part of.
  • We also clean up any topics that become empty after a client leaves.
  • The ws.on('error') handler catches any communication errors.

Client: Connecting & Subscribing

Now let's look at the client side, typically running in a web browser. We'll use the native WebSocket API.

This code snippet connects to our server and sends a subscribe message for a specific topic.

Remember to open this HTML file in a browser, and have your Node.js server running!

<!-- index.html -->
<!DOCTYPE html>
<html>
<head><title>Pub/Sub Client</title></head>
<body>
  <h1>Pub/Sub Client</h1>
  <p>Status: <span id="status">Disconnected</span></p>
  <ul id="messages"></ul>

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

    ws.onopen = () => {
      statusElem.textContent = 'Connected';
      console.log('Connected to server');
      // Subscribe to a topic
      ws.send(JSON.stringify({ action: 'subscribe', topic: 'chat:general' }));
      ws.send(JSON.stringify({ action: 'subscribe', topic: 'news' }));
    };

    ws.onclose = () => {
      statusElem.textContent = 'Disconnected';
      console.log('Disconnected from server');
    };

    ws.onerror = (error) => {
      console.error('WebSocket Error:', error);
    };

    // Message handling in the next scene
  </script>
</body>
</html>

Client: Receiving & Displaying

Once subscribed, the client needs to listen for incoming messages from the server. The ws.onmessage event is where this happens.

When a message arrives, we parse its JSON content and can display it to the user, perhaps filtering or formatting based on the message's topic.

Try opening multiple browser tabs, subscribing to the same topic, and then publishing a message from one tab (e.g., via the console) to see it appear in others!

<!-- index.html (continued script part) -->
    // ... (ws.onopen, ws.onclose, ws.onerror from previous scene)

    ws.onmessage = event => {
      const data = JSON.parse(event.data);
      console.log('Received:', data);

      if (data.type === 'message') {
        const listItem = document.createElement('li');
        listItem.textContent = `[${data.topic}] ${data.payload}`;
        messagesElem.appendChild(listItem);
      } else if (data.status === 'subscribed') {
        const listItem = document.createElement('li');
        listItem.textContent = `Successfully subscribed to '${data.topic}'.`;
        messagesElem.appendChild(listItem);
      } else if (data.error) {
        console.error('Server error:', data.error);
        const listItem = document.createElement('li');
        listItem.style.color = 'red';
        listItem.textContent = `Error: ${data.error}`; 
        messagesElem.appendChild(listItem);
      }
    };

    // Example of how a client could publish a message (e.g., via a button click)
    // ws.send(JSON.stringify({ action: 'publish', topic: 'chat:general', payload: 'Hello from client!' }));
  </script>
</body>
</html>

Advanced Pub/Sub Patterns

While our basic Pub/Sub system is functional, real-world applications often need more:

  • Unsubscribe: A client should be able to stop receiving messages for a topic. This would involve a new message action (e.g., { "action": "unsubscribe", "topic": "news" }) and server-side logic to remove the client from the topic's subscription set.
  • Topic Hierarchies: Allowing subscriptions to patterns like news.* to receive all news sub-topics.
  • Message Persistence: Storing messages so new subscribers can receive past messages (e.g., chat history).

Quick Check

Consider the Pub/Sub system we just built. Which component is primarily responsible for deciding which subscribers receive a message published to a specific topic?

Recap & Beyond

Congratulations! You've learned how to design and implement a fundamental Publish/Subscribe messaging system using WebSockets.

We covered the core components (Publisher, Subscriber, Topic, Broker), defined message formats, and built both the server-side broker logic and client-side subscription/reception.

Pub/Sub is a foundational pattern for many real-time applications. Experiment with adding unsubscribe functionality, more complex topic management, or integrating with external message queues for larger scale.

คำถามที่พบบ่อย

บทเรียน “การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส WebSockets & Realtime Systems Programming ให้อัปเกรดเป็น CoddyKit PRO คอร์ส WebSockets & Realtime Systems Programming มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ”

ออกแบบและสร้างระบบเผยแพร่และสมัครรับผ่าน WebSockets เพื่อกระจายข้อความตามหัวข้อ คุณปฏิบัติ WebSockets & Realtime Systems Programming ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน WebSockets & Realtime Systems Programming หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน WebSockets & Realtime Systems Programming บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 1 จากทั้งหมด 4 บทเรียน

บทเรียน “การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน WebSockets & Realtime Systems Programming นี้ได้ไหม

ได้ บทเรียน WebSockets & Realtime Systems Programming ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. การใช้งานการส่งข้อความแบบเผยแพร่และสมัครรับ
  2. คำขอและการตอบกลับผ่าน WebSockets
  3. การสตรีมแบบสองทิศทางและการควบคุมการไหล
  4. แรงดันย้อนกลับและการรวมกลุ่มข้อความ
← กลับไปที่ WebSockets & Realtime Systems Programming