distributor/client-example/index.js
2025-04-20 09:51:46 -06:00

40 lines
1.2 KiB
JavaScript

const WebSocket = require('ws');
var retries = 0;
function connectWebSocket() {
console.log('Attempting to connect to WebSocket...');
const ws = new WebSocket('wss://iem-alerter.ko4wal.radio/iem');
ws.on('open', () => {
console.log('Connected to WebSocket');
ws.send(JSON.stringify({ type: 'subscribe', channel: 'botstalk' }));
retries = 0; // Reset retries on successful connection
});
ws.on('message', (data) => {
console.log(JSON.parse(data));
});
ws.on('close', () => {
console.log('WebSocket connection closed. Reconnecting...');
retries++;
const retryDelay = Math.min(5000, Math.pow(2, retries) * 100);
console.log(`Retrying connection in ${retryDelay} ms...`);
setTimeout(connectWebSocket, retryDelay);
});
ws.on('error', (err) => {
console.error('WebSocket error:', err);
ws.close(); // Ensure the connection is closed before retrying
});
}
connectWebSocket();
process.on('uncaughtException', (err) => {
console.error('Unhandled exception:', err.message);
setTimeout(connectWebSocket, 1000); // Retry after 1 second
});
process.on('unhandledRejection', (reason) => {
console.error('Unhandled rejection:', reason);
setTimeout(connectWebSocket, 1000); // Retry after 1 second
});