An introduction to WebSockets.

Spread the love

WebSockets provides a  bidirectional persistent connection between a server and client. Using WebSockets, either the client or the server can initiate the connection.

The difference between TCP and WebSockets are twofold:

  1. TCP are request/reply model wherein the client sends a request and the server sends back a reply. Whereas WebSockets are duplex, both client and server can send and receive messages.
  2. WebSockets are also persistent, a WebSocket connection is opened and reused by the client.

For the server to keep a track of whether a client is connected or not, it uses heartbeat signals which are periodic messages that the server sends to the client to keep the socket alive.

There are a few libraries that provide simple client and server implementations of WebSockets, One of the fastest and lightest libraries is WS , WS has fewer features comparatively but your server can handle many open WS sockets than those of the other libraries. The other popular library is socket.io. Socket.io has lots of additional features like automatic reconnection, handling CORS issues, Broadcasting, etc.

One of the disadvantages of WebSockets is they are harder to scale  than normal TCP due to the persistent connections. To scale websockets on more than one server, you will need a publisher/subscriber broker thats connected to your servers that maintains the state between servers so that when a client connects to one server and then connects to another server, the new server gets the current state of the client.