WebSocket compartido (comunicación entre pestañas)
WebSocket compartido permite que varias pestañas del navegador compartan una única conexión WebSocket mediante la API SharedWorker.
¿Por qué usar WebSocket compartido?
Sin WebSocket compartido:
- Cada pestaña crea su propia conexión
- 5 pestañas = 5 conexiones WebSocket
- Mayor carga en el servidor
- Estado inconsistente entre pestañas
Con WebSocket compartido:
- Todas las pestañas comparten una misma conexión
- 5 pestañas = 1 conexión WebSocket
- Menor carga en el servidor
- Estado sincronizado entre pestañas
Uso básico
const ws = Odac.ws('/chat', {shared: true})
ws.on('message', data => {
console.log('Message received in this tab:', data)
})
ws.send({message: 'Hello from this tab'})
Ejemplo real: sistema de notificaciones
// All tabs share the same notification connection
const notifications = Odac.ws('/notifications', {
shared: true,
autoReconnect: true
})
notifications.on('open', () => {
console.log('Notification system connected')
})
notifications.on('message', data => {
if (data.type === 'notification') {
showNotification(data.title, data.message)
}
})
function showNotification(title, message) {
if (Notification.permission === 'granted') {
new Notification(title, {body: message})
}
}
Ejemplo de aplicación de chat
// Shared chat connection across all tabs
const chat = Odac.ws('/chat/room/general', {shared: true})
chat.on('message', data => {
if (data.type === 'message') {
addMessageToUI(data.user, data.text)
}
})
document.getElementById('send').onclick = () => {
const text = document.getElementById('input').value
chat.send({type: 'message', text})
}
// All tabs will receive the same messages
// Only one connection to the server
Compatibilidad con navegadores
WebSocket compartido usa la API SharedWorker:
- ✅ Chrome/Edge: Compatibilidad total
- ✅ Firefox: Compatibilidad total
- ❌ Safari: No compatible (recurre a un WebSocket normal)
Fallback automático:
// If SharedWorker is not available, automatically falls back to regular WebSocket
const ws = Odac.ws('/chat', {shared: true})
// Works in all browsers, shared only where supported
Gestión del ciclo de vida
La conexión compartida gestiona automáticamente su ciclo de vida:
// Tab 1 opens
const ws1 = Odac.ws('/chat', {shared: true})
// Connection established
// Tab 2 opens
const ws2 = Odac.ws('/chat', {shared: true})
// Reuses existing connection
// Tab 1 closes
// Connection stays alive (Tab 2 still using it)
// Tab 2 closes
// Connection automatically closes (no tabs using it)
Cuándo usar WebSocket compartido
Buenos casos de uso:
- Sistemas de notificaciones
- Actualizaciones en tiempo real (precios de acciones, resultados deportivos)
- Aplicaciones de chat
- Edición colaborativa
- Paneles en vivo
No recomendado para:
- Conexiones autenticadas específicas de un usuario
- Subidas y descargas de archivos
- Conexiones que requieren estado por pestaña
Comparación de rendimiento
WebSocket normal (5 pestañas):
- Conexiones al servidor: 5
- Uso de memoria: ~5MB
- Sobrecarga de red: 5x
WebSocket compartido (5 pestañas):
- Conexiones al servidor: 1
- Uso de memoria: ~1MB
- Sobrecarga de red: 1x
Depuración
Comprueba si se está usando SharedWorker:
const ws = Odac.ws('/chat', {shared: true})
// In Chrome DevTools:
// chrome://inspect/#workers
// You'll see "odac-ws-/chat" if shared