0Pricing
Edge Computing with Cloudflare Workers & Deno · Lección

WebSockets y tiempo real

Implemente aplicaciones en tiempo real con Cloudflare Workers y WebSockets para crear experiencias interactivas.

WebSockets y tiempo real es una lección gratuita de Edge Computing with Cloudflare Workers & Deno en CoddyKit. Esta es la lección 1 de 4. Puedes leer la lección completa abajo gratuitamente — luego la practicas en el navegador con un editor de código integrado y un tutor de IA 24/7. Forma parte de la ruta de aprendizaje de Edge Computing with Cloudflare Workers & Deno, y tu progreso se sincroniza en la web y la app de CoddyKit. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.

Partes de esta lección aún no han sido traducidas y se muestran en inglés.

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.

Preguntas frecuentes

¿La lección «WebSockets y tiempo real» es gratis?

Sí — el texto completo de «WebSockets y tiempo real» es gratis para leer aquí en la web. Para practicarla de forma interactiva (editor de código integrado y tutor de IA 24/7) y desbloquear el resto del curso de Edge Computing with Cloudflare Workers & Deno, actualiza a CoddyKit PRO. El curso de Edge Computing with Cloudflare Workers & Deno incluye 4 lecciones en total.

¿Qué aprenderé en «WebSockets y tiempo real»?

Implemente aplicaciones en tiempo real con Cloudflare Workers y WebSockets para crear experiencias interactivas. Practicas Edge Computing with Cloudflare Workers & Deno con código real que ejecutas directamente en el navegador, y un tutor de IA 24/7 responde tus preguntas mientras trabajas en la lección.

¿Necesito experiencia previa para empezar Edge Computing with Cloudflare Workers & Deno?

No se requiere experiencia previa. Edge Computing with Cloudflare Workers & Deno en CoddyKit está estructurado para principiantes hasta estudiantes avanzados, así que puedes empezar aquí o desde el inicio y avanzar a tu ritmo. Esta es la lección 1 de 4.

¿Cuánto tiempo toma la lección «WebSockets y tiempo real»?

La mayoría de las lecciones de CoddyKit toman alrededor de 5–10 minutos. Cada una es compacta e interactiva, así que avanzas constantemente y retomas exactamente por donde dejaste en la web y la app.

¿Puedo escribir y ejecutar código en esta lección de Edge Computing with Cloudflare Workers & Deno?

Sí. Cada lección de Edge Computing with Cloudflare Workers & Deno incluye un editor de código integrado, así que escribes y ejecutas código real directamente en tu navegador y obtienes retroalimentación instantánea de IA — sin configuración local necesaria.

Todas las lecciones de este curso

  1. WebSockets y tiempo real
  2. Colas y tareas asíncronas
  3. Service Bindings e integraciones
  4. Cron Triggers y Workers programados
← Volver a Edge Computing with Cloudflare Workers & Deno