본문 바로가기
C.W.K.
Stream
Lesson 06 of 07 · published

바이너리 프로토콜

~13 min · protocol, binary, msgpack, protobuf

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

JSON 의 비용이 커질 때

JSON 은 장황하고 해석이 느리며 부동소수점 값을 작게 담지 못해. 초당 60프레임 게임 상태, 100Hz 시장 시세, 센서 스트림처럼 빈도가 높거나 수치 중심인 데이터에서는 이 부담이 대역폭 비용과 프레임 누락으로 나타나. 대표적인 바이너리 형식은 바로 대체할 수 있고 스키마가 없는 MessagePack 과, 작지만 스키마가 필수인 Protocol Buffers 야.

MessagePack: JSON 과 닮았지만 더 작고 빨라

MessagePack 은 객체, 배열, 숫자, 문자열, 불리언, null 같은 JSON 형 구조를 약 30% 더 작은 바이너리 프레임으로 인코딩하고 훨씬 빠르게 해석해. 별도 스키마도 필요 없어서 JSON 비용이 문제가 될 때 먼저 고려하기 좋아.

Protocol Buffers: 스키마 기반의 가장 작은 형식

Protobuf 는 .proto 스키마와 코드 생성이 필요하지만 페이로드를 약 60% 줄이고 해석 속도도 가장 빨라. 스키마 자체가 문서이자 버전 관리 기준이 되지. 프로토콜이 안정됐고 데이터 규모가 준비 비용을 정당화할 때 가치가 있어.

Code

브라우저와 Python 에서 MessagePack 쓰기·javascript
// Browser side, with msgpack-lite or msgpackr
import { encode, decode } from 'msgpackr';

ws.binaryType = 'arraybuffer';
ws.send(encode({ x: 150.5, y: 300.2, id: 42, flags: 0b0001 }));

ws.onmessage = (e) => {
  if (e.data instanceof ArrayBuffer) {
    const data = decode(new Uint8Array(e.data));
    applyState(data);
  }
};
서버에서 msgpack 처리하기·python
import msgpack
from fastapi import WebSocket

@app.websocket('/ws/binary')
async def binary(websocket: WebSocket):
    await websocket.accept()
    while True:
        raw = await websocket.receive_bytes()
        data = msgpack.unpackb(raw)
        result = process(data)
        await websocket.send_bytes(msgpack.packb(result))
형식 비교·text
| Format     | Size (typical) | Parse speed | Schema required |
| ---------- | -------------- | ----------- | --------------- |
| JSON       | baseline       | slowest     | no              |
| MessagePack| ~30% smaller   | fast        | no              |
| Protobuf   | ~60% smaller   | fastest     | yes (.proto)    |

External links

Exercise

필드 50개짜리 게임 상태 딕셔너리를 JSON, MessagePack, Protobuf 로 직렬화해. JavaScript 와 Python 에서 각각 바이트 크기, 인코딩 시간, 디코딩 시간을 측정해 표로 만들어. 초당 60프레임 멀티플레이어라면 무엇을 고를지, 분당 한 번 오는 알림이라면 무엇을 고를지도 적어.

Progress

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

댓글 0

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

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