JAVASCRIPT
Real-time Data with WebSocket API Client (JavaScript)
Connect to a WebSocket API in JavaScript to enable real-time, bi-directional communication, sending messages and handling live data updates efficiently.
function createWebSocketClient(url, onMessageCallback, onOpenCallback, onCloseCallback, onErrorCallback) {
const ws = new WebSocket(url);
ws.onopen = (event) => {
console.log('WebSocket connection opened:', event);
if (onOpenCallback) onOpenCallback(event);
// Example: Send a message upon connection
// ws.send(JSON.stringify({ type: 'hello', payload: 'client connected' }));
};
ws.onmessage = (event) => {
console.log('WebSocket message received:', event.data);
try {
const data = JSON.parse(event.data);
if (onMessageCallback) onMessageCallback(data);
} catch (e) {
console.warn('Failed to parse WebSocket message as JSON:', event.data);
if (onMessageCallback) onMessageCallback(event.data); // Pass raw data if not JSON
}
};
ws.onclose = (event) => {
console.log('WebSocket connection closed:', event.code, event.reason);
if (onCloseCallback) onCloseCallback(event);
// Optionally implement reconnection logic here
};
ws.onerror = (event) => {
console.error('WebSocket error occurred:', event);
if (onErrorCallback) onErrorCallback(event);
};
return {
sendMessage: (message) => {
if (ws.readyState === WebSocket.OPEN) {
ws.send(typeof message === 'object' ? JSON.stringify(message) : message);
} else {
console.warn('WebSocket is not open. Message not sent:', message);
}
},
closeConnection: () => {
ws.close();
},
getReadyState: () => ws.readyState
};
}
// Example Usage:
// const WS_URL = 'ws://localhost:8080/ws'; // Or wss:// for secure connections
// const wsClient = createWebSocketClient(
// WS_URL,
// (data) => {
// console.log('Handled real-time data:', data);
// // Update UI, display notifications, etc.
// },
// () => console.log('Client connected successfully!'),
// (event) => console.log('Client disconnected.'),
// (error) => console.error('Client error!')
// );
// // To send a message after a delay:
// // setTimeout(() => {
// // wsClient.sendMessage({ type: 'chat_message', content: 'Hello from client!' });
// // }, 3000);
// // To close the connection:
// // setTimeout(() => {
// // wsClient.closeConnection();
// // }, 10000);
How it works: This JavaScript snippet provides a reusable function to create a WebSocket client. It establishes a connection to a specified URL and sets up event listeners for `open`, `message`, `close`, and `error` events. Callbacks are used to handle incoming messages (parsing JSON if possible), connection status changes, and errors, allowing for real-time, bi-directional data exchange with a WebSocket API.