C.W.K.
Stream
Lesson 03 of 08 · published

Message 보내기 & 받기

~12 min · browser, send, json, binary

Level 0Poller
0 XP0/60 lessons0/10 achievements
0/120 XP to next level120 XP to go0% complete

send() 가 string 만 받는 거 아냐

ws.send() 는 string (text frame), ArrayBuffer, Blob, 또는 Uint8Array 같은 typed array (binary frame) 다 받아. 브라우저가 framing 처리해. API 레벨에 chunking 없어 — send() 한 번이 logical message 하나.

JSON 이 default protocol

application 의 95% 는 wire format 이 JSON: 내보낼 때 stringify, 들어올 때 parse. type field (Track 5) 와 짝지으면 충분히 쓸만한 application protocol 완성.

Binary type 과 DataView

compact wire format — game state, market data, custom protocol — 엔 ws.binaryType = 'arraybuffer' 설정해서 binary 가 Blob 대신 ArrayBuffer 로 들어오게. 그 다음 DataView 로 알려진 byte offset 에서 typed value 읽고 써. JSON 대비 절감 극적: position update 가 binary 로 8-16 byte vs JSON 50+ byte.

bufferedAmount 과 backpressure

네트워크가 빼낼 수 있는 속도보다 빨리 send 하면 byte 가 ws.bufferedAmount 에 쌓여. 'drained' callback 없어 — poll 해. 대부분의 앱엔 무관; 빠르게 fan out 하는 앱 (cursor, position broadcast) 은 bufferedAmount 가 몇 KB 위로 오르면 throttle.

Code

보내는 모든 방법·javascript
// Plain string -> text frame
ws.send('hello');

// JSON envelope (the dominant pattern)
ws.send(JSON.stringify({
  type: 'chat.message',
  data: { room: 'general', text: 'Hi everyone!' }
}));

// Raw bytes from typed array
const bytes = new Uint8Array([0x48, 0x65, 0x6c, 0x6c, 0x6f]);
ws.send(bytes);

// ArrayBuffer with structured layout
const buf = new ArrayBuffer(8);
const view = new DataView(buf);
view.setUint32(0, 42, /* littleEndian */ true);
view.setFloat32(4, 3.14, true);
ws.send(buf);

// Blob (e.g. a small image you assembled in JS)
const blob = new Blob([bytes], { type: 'application/octet-stream' });
ws.send(blob);
Backpressure 인식하는 sender·javascript
const HIGH_WATERMARK = 16 * 1024; // 16 KB

function sendWithBackpressure(ws, data) {
  if (ws.bufferedAmount < HIGH_WATERMARK) {
    ws.send(data);
    return true;
  }
  // Skip this update or queue for later.
  return false;
}

External links

Exercise

이전 lesson 의 echo client 수정: 100 byte JSON message 10,000 개를 tight loop 로 send. setInterval 로 sampling 해서 ws.bufferedAmount 를 시간에 대해 plot. 같은 payload size 의 Uint8Array 로 바꿔서 반복. drain 속도 비교.

Progress

Progress is local-only — sign in to sync across devices.
이 페이지에서 버그를 발견하셨거나 피드백이 있으세요?문제 신고

댓글 0

🔔 답글 알림 (로그인 필요)
로그인댓글을 남기려면 로그인해 주세요.

아직 댓글이 없어요. 첫 댓글을 남겨보세요.