JAVASCRIPT
Client-Side Real-time Data Synchronization with WebSockets
Implement real-time data updates in your web application using WebSockets, enabling instant communication and live content display.
const socket = new WebSocket('ws://localhost:8080/ws'); // Replace with your WebSocket server URL
socket.onopen = (event) => {
console.log('WebSocket connection opened:', event);
// Send an initial message or handshake if needed
socket.send(JSON.stringify({ type: 'HEARTBEAT', payload: 'Client Connected' }));
};
socket.onmessage = (event) => {
const message = JSON.parse(event.data);
console.log('Received message:', message);
switch (message.type) {
case 'NEW_ITEM':
console.log('New item received:', message.payload);
// Update UI with new item
displayNewItem(message.payload);
break;
case 'ITEM_UPDATED':
console.log('Item updated:', message.payload);
// Update specific item in UI
updateExistingItem(message.payload);
break;
case 'ERROR':
console.error('WebSocket error from server:', message.payload);
// Display error message to user
break;
default:
console.log('Unknown message type:', message.type);
}
};
socket.onclose = (event) => {
if (event.wasClean) {
console.log(`WebSocket connection closed cleanly, code=${event.code} reason=${event.reason}`);
} else {
console.error('WebSocket connection died unexpectedly');
}
// Attempt to reconnect after a delay
setTimeout(() => {
console.log('Attempting to reconnect...');
// Re-initialize WebSocket connection logic here
// For simplicity, this example just logs. A robust solution would have backoff logic.
}, 5000);
};
socket.onerror = (error) => {
console.error('WebSocket error:', error);
};
// Example function to send data
function sendUpdate(data) {
if (socket.readyState === WebSocket.OPEN) {
socket.send(JSON.stringify(data));
console.log('Sent data:', data);
} else {
console.warn('WebSocket not open, cannot send data.');
}
}
// Dummy UI update functions
function displayNewItem(item) {
const itemsList = document.getElementById('items-list');
if (itemsList) {
const listItem = document.createElement('li');
listItem.textContent = `New: ${item.name} (ID: ${item.id})`;
itemsList.appendChild(listItem);
}
}
function updateExistingItem(item) {
console.log(`Updating item with ID: ${item.id} to new value: ${item.name}`);
// Find and update item in UI based on ID
}
How it works: This JavaScript snippet demonstrates how to establish and manage a client-side WebSocket connection for real-time data synchronization. It listens for `open`, `message`, `close`, and `error` events. Upon receiving a message, it parses the JSON payload and dispatches actions based on a `type` property, enabling dynamic updates to the user interface without constant polling. Includes basic reconnection logic for resilience.