TechLead
Principiante
15 min
Guía completa

Introducción a la Web en Tiempo Real

Comprende la comunicación en tiempo real, por qué es importante y qué tecnologías la hacen posible

¿Qué es la comunicación en tiempo real?

La comunicación en tiempo real permite el intercambio de datos de forma inmediata entre clientes y servidores (o directamente entre clientes) sin la espera del modelo tradicional de petición‑respuesta. En lugar de recargar la página, las actualizaciones aparecen al instante.

Ejemplos comunes: mensajes de chat que llegan al instante, precios de acciones en vivo, juegos multijugador sincronizados, y documentos colaborativos con cursores en tiempo real.

🎯 Casos de uso en tiempo real

Comunicación

  • • Chats y mensajería (Slack, Discord)
  • • Videollamadas (Zoom, Google Meet)
  • • Notificaciones y alertas

Colaboración

  • • Edición simultánea (Google Docs, Figma)
  • • Pizarras colaborativas
  • • Juegos multijugador

Datos en vivo

  • • Cotizaciones y trading
  • • Marcadores deportivos
  • • Paneles IoT

Social

  • • Streaming en vivo (Twitch, YouTube Live)
  • • Reacciones y feeds en tiempo real
  • • Indicadores de presencia (online/escribiendo)

La evolución: de polling a push

Para entender el tiempo real moderno, veamos cómo evolucionó la web:

1. HTTP tradicional (request‑response)

// The classic model - client always initiates
// User clicks "Refresh" or waits for page reload
fetch('/api/messages')
  .then(res => res.json())
  .then(messages => updateUI(messages));

// Problem: No way for server to notify client of new data!

En HTTP tradicional, el cliente siempre inicia. El servidor no puede “empujar” datos por sí mismo.

2. Short Polling

// Short polling - repeatedly ask "anything new?"
function pollForUpdates() {
  setInterval(async () => {
    const response = await fetch('/api/messages?since=' + lastTimestamp);
    const newMessages = await response.json();
    
    if (newMessages.length > 0) {
      lastTimestamp = newMessages[newMessages.length - 1].timestamp;
      displayMessages(newMessages);
    }
  }, 3000); // Check every 3 seconds
}

// Problems:
// - Wastes bandwidth (mostly empty responses)
// - Wastes server resources (constant requests)
// - Not truly real-time (up to 3 second delay)
// - Battery drain on mobile devices

3. Long Polling

// Long polling - "hold my request until you have something"
async function longPoll() {
  while (true) {
    try {
      // This request stays open until server has new data
      // or timeout occurs (usually 30-60 seconds)
      const response = await fetch('/api/messages/subscribe', {
        timeout: 60000
      });
      
      const messages = await response.json();
      displayMessages(messages);
      
    } catch (error) {
      // Reconnect on error or timeout
      await sleep(1000);
    }
  }
}

Reduce peticiones vacías, pero aún genera overhead HTTP y conexiones repetidas.

4. Server‑Sent Events (SSE)

// SSE - server can push text data to client
const eventSource = new EventSource('/api/events');

eventSource.onmessage = (event) => {
  const data = JSON.parse(event.data);
  displayMessage(data);
};

eventSource.onerror = (error) => {
  console.error('SSE error:', error);
  // EventSource auto-reconnects!
};

Ideal para actualizaciones unidireccionales (servidor → cliente) con reconexión automática.

5. WebSockets

// WebSocket - full-duplex, persistent connection
const socket = new WebSocket('wss://api.example.com/ws');

socket.onopen = () => {
  console.log('Connected!');
  socket.send(JSON.stringify({ type: 'subscribe', channel: 'chat' }));
};

socket.onmessage = (event) => {
  const message = JSON.parse(event.data);
  displayMessage(message);
};

Conexión persistente y bidireccional, ideal para chats, juegos y colaboración.

6. WebRTC

// WebRTC - peer-to-peer, no server in the middle!
const peerConnection = new RTCPeerConnection(config);

// Get local video/audio
const stream = await navigator.mediaDevices.getUserMedia({ 
  video: true, 
  audio: true 
});

// Add tracks to peer connection
stream.getTracks().forEach(track => {
  peerConnection.addTrack(track, stream);
});

Comunicación P2P con latencia mínima, especialmente para audio y video.

Comparación de tecnologías

Tecnología Dirección Protocolo Ideal para
Polling Cliente → Servidor HTTP Sistemas legacy, actualizaciones simples
Long Polling Servidor → Cliente HTTP Fallback detrás de proxies
SSE Servidor → Cliente HTTP Feeds y notificaciones
WebSocket Bidireccional WS/WSS Chat, juegos, colaboración
WebRTC Punto a punto UDP/SCTP Videollamadas, intercambio de archivos

Cómo elegir la tecnología adecuada

// Decision tree for real-time technology choice:

function chooseRealtimeTech(requirements) {
  // Need peer-to-peer media/video?
  if (requirements.peerToPeer || requirements.videoStreaming) {
    return 'WebRTC';
  }
  
  // Need bidirectional communication?
  if (requirements.clientToServer && requirements.serverToClient) {
    // High frequency updates or gaming?
    if (requirements.highFrequency || requirements.gaming) {
      return 'WebSocket';
    }
    // Moderate updates with fallback needs?
    return 'Socket.io'; // Handles fallbacks automatically
  }
  
  // Only server → client updates?
  if (requirements.serverToClient) {
    // Simple notifications/feeds?
    if (requirements.simple && !requirements.binary) {
      return 'SSE'; // Simplest API, auto-reconnect
    }
    return 'WebSocket';
  }
  
  // Infrequent updates, simplicity preferred?
  if (requirements.infrequent) {
    return 'Long Polling';
  }
  
  return 'WebSocket'; // Safe default
}

⚠️ Retos del tiempo real

Gestión de conexiones

  • • Manejar desconexiones
  • • Reintentos con backoff
  • • Sincronizar estado tras reconectar

Escalado

  • • Cada conexión consume memoria
  • • Difusión entre múltiples servidores
  • • Límites de conexiones simultáneas

Seguridad

  • • Autenticación de conexiones persistentes
  • • Rate limiting de mensajes
  • • Validación de datos entrantes

Red

  • • NAT traversal (WebRTC)
  • • Restricciones de firewall/proxy
  • • Cambios de red móvil

💡 Lo que aprenderás en este curso

  • Protocolos WebSocket y su ciclo de vida
  • Servidores en Node.js para tiempo real
  • Socket.io y sus ventajas
  • Server‑Sent Events para actualizaciones unidireccionales
  • Arquitectura WebRTC P2P
  • Señalización y conexión entre pares
  • Streaming de video en tiempo real
  • Patrones y escalado de apps en vivo