पाठ 13 / 32
The Browser WebSocket API
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Use the WebSocket constructor, events, readyState, send, binaryType and bufferedAmount, and predict the order events fire in.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
Four events and one method
new WebSocket(url, protocols?) starts the handshake asynchronously and returns immediately with readyState 0 (CONNECTING). Later it becomes 1 (OPEN), then 2 (CLOSING) and 3 (CLOSED). You react to four events: open, message (with event.data), error and close (with code, reason, wasClean). The error event carries almost no detail on purpose, so log the following close event instead. send() accepts strings, Blob, ArrayBuffer or typed arrays; calling it while still CONNECTING throws an InvalidStateError, which is why sending belongs inside onopen. Binary messages arrive as Blob by default; set ws.binaryType = 'arraybuffer' to get ArrayBuffers. send() never blocks: data queues in the browser, and bufferedAmount reports how many bytes are still waiting, which matters when you upload a lot. Note what is missing: no custom headers, no automatic reconnection and no request/response pairing. Those are your job, or a library's.
Client, server and handlers
The browser's WebSocket object talks to a server library, which dispatches each incoming message to your handler code. The same picture holds whether the server is Node.js, Python, Go or Java.
Tracing when each handler runs
The server here replies hi <message> and then closes with 1000. Watch how the synchronous code finishes before any network event fires.
const ws = new WebSocket('ws://localhost:8090');
ws.onopen = () => ws.send('hello');
ws.onmessage = (e) => console.log('got', e.data);
ws.onclose = (e) => console.log('closed', e.code);
console.log('state', ws.readyState);
- Line 1: The constructor only *starts* the handshake; it returns at once.
- Line 2: Assigning `onopen` registers a handler. Nothing is sent yet; the socket is not open.
- Line 4: `onmessage` and `onclose` are registered the same way, still synchronously.
- Line 5: The script reaches this line before the handshake completes, so it prints 0.
- Line 2: The 101 response arrives; the event loop fires `open` and the handler sends `hello`.
- Line 3: The server's reply arrives as a `message` event.
- Line 4: The server sends a close frame with 1000; after the handshake the `close` event fires.
Do not send before open
ws.send() right after new WebSocket() throws because the socket is still CONNECTING. Either send inside open, or keep an outbox array and flush it when open fires; reconnecting clients need that outbox anyway.
त्वरित जाँच: What does `console.log(ws.readyState)` print on the line straight after `new WebSocket(url)`?
- 0, because the handshake has only started
- 1, because the constructor waits for the handshake
- 3, because no server has answered
- It throws until the socket opens
Answer
0, because the handshake has only started — The constructor is non-blocking. The socket stays CONNECTING (0) until the 101 response is processed by the event loop.