BACK
Use casesWebSocket basics — incoming and outgoing messages
Use cases · 44

WebSocket basics — incoming and outgoing messages

Pattern

A WebSocket is a two-way channel. Subscribe means "listen to the server". next on the socket means "send to the server". Not to be confused with HTTP, where request/response is strictly one-to-one.

The problem it solves

The callback API socket.on('message', ...) and socket.send(...) sprawls across component handlers, cleans up poorly on destroy, and easily leaves a "zombie listener" after you leave the page.

Operators and why they matter

  • Subject simulates the duplex channel: subscribe for incoming, next for outgoing.
  • In reality, use webSocket from rxjs/webSocket — it gives exactly this model with socket.next(command).

Gotchas

  • HTTP completes on its own; a WebSocket doesn't. It can live for hours and needs explicit teardown and reconnect.
  • Don't create a new socket on every subscribe in a component. One socket in a singleton service; components subscribe to derived streams.
  • You can't swallow socket errors. You need either a reconnect or an explicit offline state in the UI.

What you get

The incoming and outgoing sides of the channel are clearly separated. Each is easy to test on its own.

script.ts // TypeScript
CONSOLE · Console output
Hit Run to see the result...