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

Event & Command Patterns

~11 min · protocol, events, commands, pubsub

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

Three patterns, often combined

Event: server pushes, client reacts. Notifications, price updates, presence — anything the user did not ask for in this moment. Command: client tells server to do something; server may or may not respond. Sending a chat message, updating profile, joining a room. Pub/Sub: client explicitly subscribes to topics; server only sends messages for subscribed topics. Useful when one connection multiplexes many independent feeds.

Most apps use all three

A trading platform: pub/sub for market data (subscribe to symbols), commands for placing orders, events for fills. A chat app: pub/sub for joining rooms, commands for sending messages, events for typing/presence. The patterns compose; they are not exclusive.

Code

Event handlers (server -> client)·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;
  }
};
Commands (client -> server)·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 style·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

Re-classify your protocol from the previous lesson exercise: which messages are events, which are commands, which are pub/sub? Write down the answer per type. If a single type sits in two categories, your protocol is probably overloaded — split it.

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.