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

이벤트와 명령 패턴

~11 min · protocol, events, commands, pubsub

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

자주 함께 쓰는 세 패턴

이벤트 는 서버가 밀어 주고 클라이언트가 반응하는 메시지야. 알림, 가격 갱신, 접속 상태처럼 사용자가 바로 요청하지 않은 정보가 해당해. 명령 은 클라이언트가 서버에 어떤 일을 시키는 메시지로, 서버가 응답할 수도 있고 아닐 수도 있어. 채팅 보내기, 프로필 갱신, 방 참여가 예야. Pub/Sub 에서는 클라이언트가 주제를 명시적으로 구독하고 서버는 구독한 주제의 메시지만 보내. 연결 하나에서 여러 독립 정보 흐름을 함께 전달할 때 유용해.

대부분의 앱은 셋을 모두 써

거래 플랫폼은 시장 데이터에 종목 구독 Pub/Sub, 주문 제출에 명령, 체결 알림에 이벤트를 써. 채팅 앱은 방 참여에 Pub/Sub, 메시지 보내기에 명령, 입력 중 표시와 접속 상태에 이벤트를 쓰지. 세 패턴은 함께 쓰는 것이지 서로 배타적이지 않아.

Code

이벤트 처리기(서버 → 클라이언트)·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;
  }
};
명령(클라이언트 → 서버)·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

이전 레슨의 프로토콜을 다시 분류해. 어떤 메시지가 이벤트이고 어떤 것이 명령이며 어떤 것이 Pub/Sub 인지 type 별로 적어. 한 type 이 두 범주에 걸친다면 역할이 너무 많이 실린 것이니 분리해.

Progress

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

댓글 0

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

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