Chapter 10. WebSocket
The APIs based on HTTP operate following the request-response model, where the client sends a request to the server and waits for the corresponding response. In HTTP, a server can’t initiate a connection or send a response to a client without the client making a prior request. A server can “push” information to the client multiple times, using methods like server-side events or HTTP streaming, but these methods still require an initial request from the client. Alternatively, a client can poll the server (send requests) for new information, using short-polling (a new TCP connection is established for each request) or long-polling (a single, long-lived TCP connection is reused for multiple requests).
The goal of WebSocket is to provide simultaneous bidirectional communication. In WebSocket, both the client and server can send messages to each other independently, without adhering to the request-response model. This is achieved by switching from HTTP to a custom, TCP-based protocol (WebSocket), which supports a full-duplex transmission mode.
When discussing WebSocket, asynchronous communication is often mentioned.1 WebSocket is not inherently asynchronous.2 Synchronous implementations of WebSocket clients and servers exist,3 but using WebSocket asynchronously has benefits like efficiently managing multiple connections and improving responsiveness.4
In this chapter, you’ll be exposed to the WebSocket protocol, its opening handshake process, and how to implement ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access