function decode(view) { const type = view.getUint8(0); const len = view.getUint32(1, false); // big-endian const body = new Uint8Array(view.buffer, 5, len); return { type, body };}
Step
API
Wrap buffer
new DataView(buf)
Read fields
getUint8/16/32/Float32
Slice
new Uint8Array(buf, offset, len)
9. Implementing Message Queue
Example: Async iterator queue
function makeQueue(ws) { const buf = [], waiters = []; ws.addEventListener("message", (e) => { if (waiters.length) waiters.shift()(e.data); else buf.push(e.data); }); return { async next() { if (buf.length) return buf.shift(); return new Promise(res => waiters.push(res)); } };}
Pattern
Use
Async iterator
for-await loops
EventTarget bridge
Library boundaries
Observable
RxJS integration
10. Handling Large Messages
Technique
Detail
App-level chunking
Split into ordered frames with seq
Streaming reassembly
Maintain buffer per message ID
Out-of-band transfer
Use HTTP for large blobs, WS for notify
Warning: Default ws server maxPayload is 100 MiB. Tune both client and server limits to prevent close 1009.