पाठ 16 / 32
Designing Your Message Protocol
यह पाठ अभी हिंदी में अनुवादित नहीं है, इसलिए अंग्रेज़ी में दिखाया जा रहा है।
Define typed JSON envelopes with ids, acknowledgements and timeouts on top of raw WebSocket messages.
लेखक: Rahul Agarwal · 15 साल से वेब डेवलपर
WebSocket gives you a pipe, not a protocol
A WebSocket delivers ordered messages, nothing more. It has no URLs, no methods, no status codes and no way to match a reply to a request. So every real app defines an envelope, usually JSON such as { "type": "chat", "id": 7, "payload": {...} }. The type field routes the message to a handler, much like a URL route. An id on client requests lets the server answer with { "replyTo": 7, ... }, so the client can resolve the right promise; this is how you build acknowledgements ("your message was saved") and request/response calls over a socket. Server pushes often carry a sequence number per room or stream so clients can detect gaps and resume after reconnecting. Add a v (version) field or negotiate a subprotocol early, because old mobile app builds will keep talking to your server for months. Keep payloads small; send ids and let the client fetch large objects over HTTP.
From raw message to the right audience
Every incoming message is parsed into an envelope, routed by type, and its effect is broadcast to the clients who care.
Request/acknowledgement over a socket
Each request gets an id and a pending promise with a timeout. When a reply with matching replyTo arrives, the promise resolves. A fake socket stands in for the server so the example runs on its own.
let nextId = 1;
const pending = new Map(); // id -> { resolve, timer }
function request(socket, type, payload, timeoutMs = 5000) {
const id = nextId++;
socket.send(JSON.stringify({ id, type, payload }));
return new Promise((resolve, reject) => {
const timer = setTimeout(() => {
pending.delete(id);
reject(new Error(`${type} #${id} timed out`));
}, timeoutMs);
pending.set(id, { resolve, timer });
});
}
function onMessage(raw) {
const msg = JSON.parse(raw);
const waiter = pending.get(msg.replyTo);
if (!waiter) return; // late or unknown reply: ignore
clearTimeout(waiter.timer);
pending.delete(msg.replyTo);
waiter.resolve(msg.payload);
}
// Fake socket that replies like a server would, 10 ms later.
const fakeSocket = {
send(text) {
const { id, payload } = JSON.parse(text);
const reply = { replyTo: id, payload: { saved: payload.text } };
setTimeout(() => onMessage(JSON.stringify(reply)), 10);
},
};
console.log(await request(fakeSocket, 'chat', { text: 'see you at 5' }));
console.log(await request(fakeSocket, 'chat', { text: 'bring notes' }));
Output:
{ saved: 'see you at 5' }
{ saved: 'bring notes' }Always time out pending requests
If the connection drops, replies never come. Without a timeout, the pending map grows forever and UI spinners never stop. Reject on timeout and on close, and let the caller decide whether to retry.
त्वरित जाँच: Why does a request sent over a WebSocket usually carry an `id` field?
- The WebSocket protocol rejects messages without ids
- Browsers use it to order frames
- It is required for masking
- So the client can match the server's reply to the request that caused it
Answer
So the client can match the server's reply to the request that caused it — Messages on a socket are not paired like HTTP request/response. An id echoed back as `replyTo` lets the client resolve the correct pending request.