TechLead
Intermedio
35 min
Guía completa

Implementación de WebSocket

Construye servidores y clientes WebSocket con ejemplos prácticos en Node.js

Servidor WebSocket básico

Comencemos con la librería ws en Node.js para crear un servidor simple.

// npm install ws
const WebSocket = require('ws');

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

wss.on('connection', (ws) => {
  ws.send(JSON.stringify({ type: 'welcome', message: 'Hola' }));

  ws.on('message', (data) => {
    const msg = JSON.parse(data);
    console.log('Mensaje:', msg);
  });
});

Broadcast a todos los clientes

function broadcast(message) {
  const payload = JSON.stringify(message);
  wss.clients.forEach((client) => {
    if (client.readyState === WebSocket.OPEN) {
      client.send(payload);
    }
  });
}

Cliente WebSocket

const socket = new WebSocket('ws://localhost:8080');

socket.onopen = () => {
  socket.send(JSON.stringify({ type: 'join', room: 'general' }));
};

socket.onmessage = (event) => {
  const data = JSON.parse(event.data);
  console.log('Servidor:', data);
};

Heartbeat y reconexión

function heartbeat(ws) {
  ws.isAlive = true;
}

wss.on('connection', (ws) => {
  ws.isAlive = true;
  ws.on('pong', () => heartbeat(ws));
});

setInterval(() => {
  wss.clients.forEach((ws) => {
    if (!ws.isAlive) return ws.terminate();
    ws.isAlive = false;
    ws.ping();
  });
}, 30000);

Escalado con Redis (pub/sub)

Para múltiples instancias, comparte eventos con un broker como Redis.

// Pseudocódigo
const pub = redis.createClient();
const sub = redis.createClient();

sub.subscribe('chat');
sub.on('message', (channel, message) => {
  broadcast(JSON.parse(message));
});

function publish(message) {
  pub.publish('chat', JSON.stringify(message));
}

💡 Buenas prácticas

  • ✓ Mantén una sola conexión por usuario
  • ✓ Usa mensajes pequeños y tipados
  • ✓ Implementa reconexión con backoff
  • ✓ Protege rutas con auth y rate limiting