Websockets con Express
Aunque Express por sí mismo no implementa Websockets, se puede combinar con bibliotecas como ws o socket.io para añadir funcionalidad en tiempo real.
Código del servidor (backend)
import express from 'express';
import { createServer } from 'http';
import { Server } from 'socket.io';
const app = express();
const httpServer = createServer(app);
// Configuración de Socket.IO
const io = new Server(httpServer, {
cors: { origin: "*" } // Permite conexiones desde cualquier origen
});
// Detectar nuevas conexiones
io.on('connection', (socket) => {
console.log('Cliente conectado:', socket.id);
// Escuchar eventos enviados por el cliente
socket.on('mensaje', (data) => {
console.log('Mensaje recibido:', data);
// Enviar el mensaje a todos los clientes conectados
io.emit('mensaje', data);
});
// Detectar desconexión
socket.on('disconnect', () => {
console.log('Cliente desconectado:', socket.id);
});
});
// Servir la aplicación
httpServer.listen(3000, () => {
console.log('Servidor Websocket corriendo en http://localhost:3000');
});
Código del cliente (frontend)
Para conectarse al servidor y enviar/recibir mensajes desde un navegador, se puede usar la librería Socket.IO Client. Puedes incluirla desde un CDN o instalarla vía npm si tu cliente es Node.js.
Ejemplo:
<!DOCTYPE html>
<html>
<head>
<title>Chat con Websockets</title>
<script src="https://cdn.socket.io/4.8.1/socket.io.min.js"></script>
</head>
<body>
<input id="mensaje" placeholder="Escribe un mensaje">
<button onclick="enviarMensaje()">Enviar</button>
<ul id="chat"></ul>
<script>
// Conectar al servidor
const socket = io('http://localhost:3000');
// Escuchar mensajes del servidor
socket.on('mensaje', data => {
const li = document.createElement('li');
li.textContent = data;
document.getElementById('chat').appendChild(li);
});
// Enviar mensaje al servidor
function enviarMensaje() {
const input = document.getElementById('mensaje');
const mensaje = input.value;
socket.emit('mensaje', mensaje);
input.value = '';
}
</script>
</body>
</html>