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

메시지 프로토콜 설계

~12 min · protocol, envelope, type-field

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

type 과 data 를 담는 봉투

WebSocket 은 의미를 알 수 없는 메시지 흐름만 제공하므로 구조는 애플리케이션이 더해야 해. Slack, Discord, GraphQL-WS 를 비롯한 채팅 라이브러리에서 널리 쓰는 방식은 type 문자열과 data 객체를 담은 작은 JSON 봉투야. type 필드가 data 에 어떤 스키마를 적용할지 알려 주고, 나머지 설계가 이 결정에서 뻗어 나와.

메시지 종류의 이름 공간

chat.message, chat.typing, user.joined, user.status, room.join, game.move 처럼 점 표기법을 써. 첫 부분은 영역, 두 번째는 동작이나 사건을 나타내. 정렬과 검색이 쉽고 자연스럽게 확장할 수 있어.

오류도 메시지야

오류 응답도 {type: 'error', code: 'rate_limited', message: '...', ref_id: 'xyz'} 같은 평범한 메시지야. 같은 봉투에 다른 스키마를 쓰는 셈이지. 오류를 특별한 전송 계층 개념으로 빼지 말고 일급 메시지로 다뤄.

Code

프로토콜 봉투 예시·json
// chat message
{
  "type": "chat.message",
  "data": {
    "room": "general",
    "text": "hello",
    "ts":   "2026-05-03T10:30:00Z"
  }
}

// system event
{
  "type": "user.joined",
  "data": { "user_id": "abc123", "username": "Alice" }
}

// error
{
  "type":    "error",
  "code":    "rate_limited",
  "message": "slow down — max 20 messages/sec",
  "ref_id":  "msg-xyz-123"
}
메시지 종류별 서버 라우터·python
async def dispatch(ws, user, msg: dict):
    handlers = {
        'chat.message': handle_chat,
        'chat.typing':  handle_typing,
        'room.join':    handle_join,
        'room.leave':   handle_leave,
        'pong':         handle_pong,
    }
    fn = handlers.get(msg.get('type'))
    if fn is None:
        await ws.send_json({
            'type': 'error',
            'code': 'unknown_type',
            'message': f"unknown type: {msg.get('type')!r}",
        })
        return
    await fn(ws, user, msg.get('data', {}))

External links

Exercise

간단한 채팅 앱의 프로토콜을 정의해. chat.message, chat.typing, user.joined, user.left, room.join, room.leave, error 의 모든 메시지 종류와 필드를 AsyncAPI 3.0 문서에 적어. 코드를 생성하지 않아도 명세를 쓰는 과정 자체가 빠진 필드를 찾아 줄 거야.

Progress

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

댓글 0

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

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