JAVASCRIPT
Consuming Real-time API Data via WebSockets in JavaScript
Learn how to establish and manage a WebSocket connection in JavaScript to receive live, real-time updates from an API, essential for dynamic web applications.
// Ensure your browser supports WebSockets or use a WebSocket polyfill if needed
// For Node.js, you'd use a library like 'ws'
const socketUrl = 'wss://echo.websocket.events'; // Example public WebSocket echo server
// Replace with your actual real-time API WebSocket endpoint
let ws = null;
const connectWebSocket = () => {
if (ws && ws.readyState === WebSocket.OPEN) {
console.log('WebSocket already connected.');
return;
}
ws = new WebSocket(socketUrl);
ws.onopen = (event) => {
console.log('WebSocket connected:', event);
// Send a message after connection is established
ws.send('Hello from client!');
};
ws.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
// Process real-time data here
try {
const data = JSON.parse(event.data);
console.log('Parsed JSON data:', data);
} catch (e) {
console.log('Received non-JSON message or parsing error.');
}
};
ws.onclose = (event) => {
console.log('WebSocket disconnected:', event);
if (event.wasClean) {
console.log(`Connection closed cleanly, code=${event.code}, reason=${event.reason}`);
} else {
// e.g. server process killed or network down
console.error('Connection died unexpectedly.');
// Attempt to reconnect after a delay
setTimeout(connectWebSocket, 5000);
}
};
ws.onerror = (error) => {
console.error('WebSocket error:', error);
ws.close(); // Close on error to trigger onclose and potential reconnect
};
};
// Initial connection attempt
connectWebSocket();
// To send messages later:
// if (ws && ws.readyState === WebSocket.OPEN) {
// ws.send(JSON.stringify({ type: 'update', payload: '...' }));
// }
// To close the connection explicitly:
// setTimeout(() => {
// if (ws && ws.readyState === WebSocket.OPEN) {
// console.log('Closing WebSocket connection...');
// ws.close(1000, 'Client initiated close'); // Code 1000 for normal closure
// }
// }, 10000);
How it works: This JavaScript snippet demonstrates how to establish and manage a WebSocket connection to consume real-time data from an API. Unlike traditional HTTP requests, WebSockets provide a full-duplex communication channel over a single TCP connection, allowing both the client and server to send messages at any time. The code illustrates how to connect, listen for incoming messages (`onmessage`), handle disconnections (`onclose`), and errors (`onerror`). It also includes a basic reconnection logic for unexpected disconnections, which is crucial for maintaining persistent real-time data streams in dynamic web applications.