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

Event & Command 패턴

~11 min · protocol, events, commands, pubsub

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

세 패턴, 자주 결합

Event: 서버 push, 클라 react. notification, price update, presence — user 가 지금 안 물어본 모든 거. Command: 클라가 서버한테 뭐 하라고; 서버가 응답할 수도 안 할 수도. chat 보내기, profile update, room join. Pub/Sub: 클라가 명시적으로 topic 구독; 서버가 구독 topic message 만 보냄. 한 connection 이 여러 독립 feed multiplex 할 때 유용.

대부분 앱이 셋 다 써

Trading 플랫폼: market data 엔 pub/sub (symbol 구독), order placement 엔 command, fill 엔 event. Chat 앱: room join 엔 pub/sub, message 보내기 엔 command, typing/presence 엔 event. 패턴 합쳐 쓰지, 배타적 아냐.

Code

Event handler (서버 -> 클라)·javascript
ws.onmessage = (e) => {
  const { type, data } = JSON.parse(e.data);
  switch (type) {
    case 'notification.new':  showToast(data); break;
    case 'price.update':      tickChart(data); break;
    case 'user.online':       updatePresence(data); break;
    case 'document.changed':  applyEdit(data); break;
  }
};
Command (클라 -> 서버)·javascript
ws.send(JSON.stringify({
  type: 'room.join',
  data: { room: 'general' }
}));

ws.send(JSON.stringify({
  type: 'chat.send',
  data: { room: 'general', text: 'hi' }
}));

ws.send(JSON.stringify({
  type: 'user.status',
  data: { status: 'away' }
}));
Pub/Sub 스타일·javascript
// Subscribe to specific channels
ws.send(JSON.stringify({
  type: 'subscribe',
  data: { channels: ['prices.BTC', 'prices.ETH', 'news.crypto'] }
}));

// Server only sends messages for these channels
ws.onmessage = (e) => {
  const msg = JSON.parse(e.data);
  // msg.channel tells you which subscription this is for
  routeByChannel(msg.channel, msg.data);
};

External links

Exercise

이전 lesson 의 protocol 재분류: 어느 message 가 event, 어느 게 command, 어느 게 pub/sub? type 별로 적어. 한 type 이 두 카테고리에 걸쳐있으면 protocol 이 overload 된 거 — 분리.

Progress

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

댓글 0

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

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