0Pricing
Edge Computing with Cloudflare Workers & Deno · Pelajaran

WebSockets & Waktu Nyata

Implementasikan aplikasi waktu nyata menggunakan Cloudflare Workers dan WebSockets untuk menghadirkan pengalaman interaktif.

WebSockets & Waktu Nyata adalah pelajaran Edge Computing with Cloudflare Workers & Deno gratis di CoddyKit. Ini adalah pelajaran 1 dari 4. Kamu bisa membaca pelajaran lengkapnya di bawah secara gratis — lalu praktikkan langsung di browser dengan editor kode bawaan dan tutor AI 24/7. Ini adalah bagian dari jalur belajar Edge Computing with Cloudflare Workers & Deno, dan progresmu tersinkronisasi di web dan aplikasi CoddyKit. Kursus Edge Computing with Cloudflare Workers & Deno mencakup 4 pelajaran total.

Bagian dari pelajaran ini belum diterjemahkan dan ditampilkan dalam bahasa Inggris.

Real-time Apps with WebSockets

What are WebSockets? They enable real-time, two-way communication between a client (like your browser) and a server. Unlike traditional HTTP requests, WebSockets keep a persistent connection open.

This is perfect for applications needing instant updates, like chat apps, live dashboards, or online games.

HTTP vs. WebSocket Connection

Traditional HTTP is stateless and request-response based. Each action needs a new request from the client.

WebSockets, however, establish a single, long-lived connection. Once open, both client and server can send messages anytime without waiting for a request.

  • HTTP: Client requests, server responds, connection closes.
  • WebSocket: Client requests upgrade, server approves, connection stays open.

The WebSocket Upgrade

Before a WebSocket connection is established, an initial HTTP request is made. The client sends an "Upgrade" header, indicating its desire to switch protocols.

If the server supports WebSockets, it responds with an "101 Switching Protocols" status code, upgrading the connection from HTTP to WebSocket protocol. This is known as the WebSocket Handshake.

Cloudflare Workers & WebSockets

Cloudflare Workers are ideal for handling WebSockets at the edge. They can act as the server endpoint, managing connections and processing real-time messages directly where your users are.

Workers provide a WebSocketPair API to easily upgrade an incoming HTTP request into a WebSocket connection, simplifying the handshake process.

Worker WebSocket Upgrade

Let's create a Worker that accepts an incoming WebSocket connection. We'll use new WebSocketPair() to manage the connection.

Try running this example. To test, you'd typically connect using a WebSocket client (e.g., a browser's developer console or a dedicated tool).

export default {
  async fetch(request) {
    const upgradeHeader = request.headers.get('Upgrade');
    if (!upgradeHeader || upgradeHeader !== 'websocket') {
      return new Response('Expected Upgrade: websocket', { status: 426 });
    }

    const { 0: client, 1: server } = new WebSocketPair();

    server.accept(); // Accept the WebSocket connection

    server.addEventListener('message', event => {
      console.log('Received message:', event.data);
      // We'll add logic to send messages back soon!
    });
    server.addEventListener('close', event => {
      console.log('WebSocket closed:', event.code, event.reason);
    });
    server.addEventListener('error', event => {
      console.error('WebSocket error:', event.message);
    });

    return new Response(null, {
      status: 101,
      webSocket: client,
    });
  },
};

WebSocket Event Listeners

Once a WebSocket connection is established, you can listen for various events on the server-side WebSocket object:

  • 'open': Connection successfully established.
  • 'message': A message is received from the client. The message data is in event.data.
  • 'close': The connection is closed by either side.
  • 'error': An error occurred on the connection.

These allow your Worker to react dynamically to client interactions.

Echoing Messages

In the previous code, we added an event listener for 'message'. Let's extend it to ensure the Worker echoes back any message it receives.

The server.send(message) method allows the Worker to send data back to the connected client. This creates a simple "echo" server.

export default {
  async fetch(request) {
    const upgradeHeader = request.headers.get('Upgrade');
    if (!upgradeHeader || upgradeHeader !== 'websocket') {
      return new Response('Expected Upgrade: websocket', { status: 426 });
    }

    const { 0: client, 1: server } = new WebSocketPair();

    server.accept();
    server.addEventListener('message', event => {
      const message = event.data;
      console.log('Received message:', message);
      // Echo the message back to the client
      server.send(`Echo from Worker: ${message}`);
    });
    server.addEventListener('close', event => {
      console.log('WebSocket closed');
    });
    server.addEventListener('error', event => {
      console.error('WebSocket error:', event);
    });

    return new Response(null, {
      status: 101,
      webSocket: client,
    });
  },
};

Real-time Broadcasting

An echo server is a good start, but many real-time apps need to send messages to multiple connected clients (broadcasting).

For example, in a chat application, when one user sends a message, all other users in the chat room should receive it.

Cloudflare Workers, being stateless by default, need a mechanism to manage these connections across requests. This is where Durable Objects become incredibly useful for maintaining state and managing multiple WebSocket connections for a shared resource.

(We'll explore Durable Objects in a later lesson!)

Securing WebSockets

Just like HTTP, WebSocket connections should be secured. Always use wss:// (WebSocket Secure) instead of ws://.

wss:// connections are encrypted using TLS/SSL, preventing eavesdropping and tampering. Cloudflare Workers handle TLS termination automatically, so your connections are secured by default when deployed.

  • Use wss:// for production.
  • Implement authentication/authorization.
  • Validate all incoming messages.

Check Your Understanding

Consider a Cloudflare Worker that aims to establish a WebSocket connection with a client.

Recap: WebSockets at the Edge

Great job! You've learned how to implement real-time communication with WebSockets using Cloudflare Workers.

  • WebSockets enable persistent, two-way communication.
  • Workers use WebSocketPair and 101 Switching Protocols for the handshake.
  • Event listeners ('message', 'close', 'error') manage connection lifecycle.
  • Always use wss:// for secure connections.

In future lessons, we'll dive into Durable Objects to manage state across multiple WebSocket connections for advanced real-time applications.

Pertanyaan yang Sering Diajukan

Apakah pelajaran “WebSockets & Waktu Nyata” gratis?

Ya — teks lengkap “WebSockets & Waktu Nyata” gratis dibaca di sini di web. Untuk praktiknya secara interaktif (editor kode bawaan dan tutor AI 24/7) dan buka sisa kursus Edge Computing with Cloudflare Workers & Deno, upgrade ke CoddyKit PRO. Kursus Edge Computing with Cloudflare Workers & Deno mencakup 4 pelajaran total.

Apa yang akan aku pelajari di “WebSockets & Waktu Nyata”?

Implementasikan aplikasi waktu nyata menggunakan Cloudflare Workers dan WebSockets untuk menghadirkan pengalaman interaktif. Kamu berlatih Edge Computing with Cloudflare Workers & Deno dengan kode praktik yang langsung kamu jalankan di browser, dan tutor AI 24/7 menjawab pertanyaanmu saat kamu mengerjakan pelajaran ini.

Apakah aku perlu pengalaman untuk memulai Edge Computing with Cloudflare Workers & Deno?

Tidak diperlukan pengalaman sebelumnya. Edge Computing with Cloudflare Workers & Deno di CoddyKit dirancang untuk pemula hingga pelajar tingkat lanjut, jadi kamu bisa memulai di sini atau dari awal dan belajar sesuai kecepatan kamu sendiri. Ini adalah pelajaran 1 dari 4.

Berapa lama pelajaran “WebSockets & Waktu Nyata” memakan waktu?

Sebagian besar pelajaran CoddyKit memakan waktu sekitar 5–10 menit. Setiap pelajaran ringkas dan interaktif, jadi kamu membuat kemajuan stabil dan melanjutkan dari tempat kamu tinggalkan di web dan aplikasi.

Bisakah aku menulis dan menjalankan kode dalam pelajaran Edge Computing with Cloudflare Workers & Deno ini?

Ya. Setiap pelajaran Edge Computing with Cloudflare Workers & Deno menyertakan editor kode bawaan, jadi kamu menulis dan menjalankan kode nyata langsung di browser dan mendapatkan umpan balik AI instan — tidak diperlukan penyiapan lokal.

Semua pelajaran dalam kursus ini

  1. WebSockets & Waktu Nyata
  2. Antrean & Tugas Asinkron
  3. Pengikatan Layanan & Integrasi
  4. Pemicu Cron dan Workers Terjadwal
← Kembali ke Edge Computing with Cloudflare Workers & Deno