concept WebSocket in category rxjs

This is an excerpt from Manning's book RxJS in Action.
Event emitters are popular mechanisms for asynchronous event-based architectures. The DOM, for instance, is probably one of the most widely known event emitters. On a server like Node.js, certain kinds of objects periodically produce events that cause functions to be called. In Node.js, the EventEmitter class is used to implement APIs for things like WebSocket I/O or file reading/writing so that if you’re iterating through directories and you find a file of interest, an object can emit an event referencing this file for you to execute any additional code.
Aside from binding to DOM events and AJAX calls, RxJS can just as easily bind to WebSockets. WebSocket (WS) is an asynchronous communication protocol that provides faster and more efficient lines of communication from client to server than traditional HTTP. This is useful for highly interactive applications like live chats, streaming services, or games. Like HTTP, WS runs on top of a TCP connection, but the advantage is that information can be passed back and forth while keeping the connection open (taking advantage of the browser’s multiplexing capabilities and the keep-alive feature). The other benefit is that servers can send content to the browser without it explicitly requesting it.
The crucial point of this process is the initial handshake that negotiates the upgrade process. The upgrade needs to happen because WebSocket uses the same ports 80 and 443 for HTTP and HTTPS, respectively (443 is used by the WebSockets Secure protocol). Routing requests through the same ports is advantageous because firewalls are typically configured to allow this information to flow freely. At a very high level, this process happens with an initial secure request by the client and a proper response by the WebSocket-supporting server, shown in figure 8.7.
Figure 8.7. The handshake negotiation process begins with the client’s GET request containing a secure key and instructions for the server to attempt to upgrade to a message-based WebSocket connection. If the server understands WebSocket, it will respond with a unique hash confirming the protocol upgrade.
![]()
From the point of view of asynchronous event messaging, you can think of WebSocket as an event emitter for client-server communication. We haven’t really talked about server-side RxJS, but little changes there. You can easily use RxJS to support both sides of the coin, starting with the server.