Building a WebSocket Client in JavaScript

WebSockets provide a persistent, full-duplex connection between browser and server — unlike HTTP requests, either side can send a message at any time without the other having to ask first.

const socket = new WebSocket('wss://chat.example.com/ws');

socket.addEventListener('open', () => {
    console.log('Connected');
    socket.send(JSON.stringify({ type: 'join', room: 'general' }));
});

socket.addEventListener('message', (event) => {
    const data = JSON.parse(event.data);
    console.log('Received:', data);
});

socket.addEventListener('close', () => {
    console.log('Disconnected - consider reconnecting here');
});

function sendMessage(text) {
    if (socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({ type: 'message', text }));
    }
}

Reconnection Isn’t Automatic

A dropped WebSocket connection stays dropped — production code needs explicit reconnection logic (often with exponential backoff) in the close handler, since the browser never retries a WebSocket connection on its own the way it might retry a fetch.