JAVASCRIPT

Integrate WebSockets for Real-time Data Updates (Client-side)

Establish a WebSocket connection in the browser to receive and display real-time updates from an API without constant polling.

const websocketUrl = 'ws://localhost:8080/realtime'; // Or wss:// for secure connections
let ws;

function connectWebSocket() {
    ws = new WebSocket(websocketUrl);

    ws.onopen = () => {
        console.log('WebSocket connected!');
        document.getElementById('status').textContent = 'Status: Connected';
        // Optionally send a message upon connection
        // ws.send(JSON.stringify({ type: 'init', payload: 'hello server' }));
    };

    ws.onmessage = (event) => {
        console.log('Received message:', event.data);
        const data = JSON.parse(event.data);
        document.getElementById('messages').innerHTML += `<p>Received: ${JSON.stringify(data)}</p>`;
        // Process real-time data here
        // E.g., update a chart, display a notification, etc.
    };

    ws.onclose = (event) => {
        console.log(`WebSocket closed: Code=${event.code}, Reason=${event.reason}, Clean=${event.wasClean}`);
        document.getElementById('status').textContent = 'Status: Disconnected';
        // Attempt to reconnect after a delay if the close was not clean or intended
        if (!event.wasClean) {
            console.log('Attempting to reconnect WebSocket in 5 seconds...');
            setTimeout(connectWebSocket, 5000);
        }
    };

    ws.onerror = (error) => {
        console.error('WebSocket error:', error);
        document.getElementById('status').textContent = 'Status: Error';
    };
}

// Initial connection
connectWebSocket();

// Example of sending a message from the client
function sendMessage() {
    if (ws && ws.readyState === WebSocket.OPEN) {
        const messageInput = document.getElementById('messageInput');
        const message = messageInput.value;
        if (message) {
            ws.send(JSON.stringify({ type: 'chat', message: message }));
            document.getElementById('messages').innerHTML += `<p>Sent: ${message}</p>`;
            messageInput.value = '';
        }
    } else {
        console.warn('WebSocket not open. Cannot send message.');
        document.getElementById('messages').innerHTML += `<p style="color:red;">Error: WebSocket not connected. Cannot send.</p>`;
    }
}

// HTML structure for testing:
// <div id="status">Status: Disconnected</div>
// <div id="messages"></div>
// <input type="text" id="messageInput" placeholder="Type a message">
// <button onclick="sendMessage()">Send</button>
How it works: This snippet demonstrates how to establish and manage a client-side WebSocket connection for real-time data updates. It sets up an event listener for `onopen`, `onmessage`, `onclose`, and `onerror` events. When `onmessage` is triggered, it parses incoming JSON data and displays it, showcasing how to process real-time information. It also includes basic error handling and a reconnection strategy for unexpected disconnections, providing a foundation for interactive web applications that require instant data synchronization.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs