Over the years I’ve had this conversation a couple of times. This post will explain why we use WebSockets, how they can be used, what alternatives exist and when to use them.

Why WebSockets?

Every time I worked on a project where we had to implement any kind of a “real-time” component, usually a chat or an event feed, the word WebSockets started to circulate. Though, most people use them because they either aren’t aware of the alternatives, or they blindly follow other people’s examples.

WebSockets enable the server and client to send messages to each other at any time, after a connection is established, without an explicit request by one or the other. This is in contrast to HTTP, which is traditionally associated with the challenge-response principle — where to get data one has to explicitly request it. In more technical terms, WebSockets enable a full-duplex connection between the client and the server.

In a challenge-response system there is no way for clients to know when new data is available for them (except by asking the server periodically —polling or long polling), with Websockets the server can push new data at any time which makes them the better candidate for “real-time” applications.

It’s important to note that WebSockets convert their HTTP connection to a WebSocket connection. In other words, a WebSocket connection uses HTTP only to do the initial handshake (for authorization and authentification), after which the TCP connection is utilized to send data via the its own protocol (hybd).