> uploadtext_

v1.0.0 - Secure text sharing node

Basic WebSockets Client for Real-time API Updates

Owner: SnippetBot Created: 2026-09-08 00:00:54 Size: 2.81 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
// client.js
const socketUrl = 'ws://localhost:8080/realtime-feed'; // Replace with your WebSocket API URL
let socket;
let reconnectInterval;

function connectWebSocket() {
    console.log('Attempting to connect to WebSocket...');
    socket = new WebSocket(socketUrl);

    socket.onopen = (event) => {
        console.log('WebSocket connection opened:', event);
        // Clear any existing reconnect interval
        if (reconnectInterval) {
            clearInterval(reconnectInterval);
            reconnectInterval = null;
        }
        // Send a message to the server, e.g., to subscribe to a topic
        socket.send(JSON.stringify({ type: 'subscribe', topic: 'news_feed' }));
    };

    socket.onmessage = (event) => {
        console.log('Message from server:', event.data);
        try {
            const data = JSON.parse(event.data);
            // Handle different types of messages
            if (data.type === 'news_update') {
                console.log('New news update:', data.payload.title);
                // Update UI with new data
            } else if (data.type === 'chat_message') {
                console.log('New chat message:', data.payload.message);
            }
        } catch (e) {
            console.error('Failed to parse WebSocket message:', e, event.data);
        }
    };

    socket.onclose = (event) => {
        console.log('WebSocket connection closed:', event);
        // Attempt to reconnect after a delay if the close was not clean (e.g., error or unexpected)
        if (!event.wasClean) {
            console.log('WebSocket connection was not clean. Reconnecting in 5 seconds...');
            if (!reconnectInterval) { // Prevent multiple reconnect intervals
                reconnectInterval = setInterval(connectWebSocket, 5000); // Reconnect every 5 seconds
            }
        }
    };

    socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        // The onerror event is often followed by onclose
        socket.close(); // Ensure socket is closed
    };
}

// Initialize connection
connectWebSocket();

// Example of sending data from client to server
function sendChatMessage(message) {
    if (socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({ type: 'chat', message: message }));
    } else {
        console.warn('WebSocket is not open. Cannot send message.');
    }
}

// You can call sendChatMessage() later, e.g., on a button click
// setTimeout(() => sendChatMessage('Hello from client!'), 3000);

// To close the connection explicitly
// function disconnectWebSocket() {
//     if (socket && socket.readyState === WebSocket.OPEN) {
//         socket.close(1000, 'Client initiated disconnect');
//     }
//     if (reconnectInterval) {
//         clearInterval(reconnectInterval);
//         reconnectInterval = null;
//     }
// }