Comparing WebSockets with polling approaches

If you have ever built a web page’s chat room by using a server-side language and a database, then you may wonder what the difference is between the WebSocket implementation and the traditional one.

Polling approach

The traditional chat room method is often implemented by using a polling approach. The client asks the server for an update periodically. The server responds to the client with either no update or the updated data. However, the traditional approach has several problems. The client does not get new data updated from the server until the next time it asks the server. This means that the data update is periodically delayed with time and the response is not instant enough. If we want to improve this issue by shortening the polling duration, then more bandwidth is utilized because clients need to keep sending requests to the server.

The following graph shows requests between the client and the server. It shows that many useless requests are sent, but the server responds to the client without any new data:

Polling approach

Long polling approach

There is a better polling approach named long polling: the client sends a request to the server and waits for the response. Instead of the traditional polling approach where the server responds with “no update”, the server does not respond at all until there is something that needs to be pushed to the server. In this approach, the server can push something to clients whenever there is an update. Once a client receives a response from the server, it creates another request and waits for the next server notification. The following graph shows the long polling approach where clients ask for updates and the server responds only when there is an update:

Long polling approach

Websocket approach

In the WebSockets approach, the number of requests are way less than the polling approach. This is because the connection between the client and server is persistent. Once the connection is established, a request from either the client side or the server side is sent only when there is any update. For instance, a client sends a message to the server when it wants to update something to the server. The server also sends messages to clients only when it needs to notify the clients of a data update. No other useless requests are sent during the connection. Therefore, less bandwidth is utilized. The following graph shows the WebSockets approach:

Websocket approach

I’ve created simple application using websocket. In this demo, We have built the server and client that connects to our WebSocket server and receives messages from the server. The message will contain the total connection count from the server.

Github repo: https://github.com/jayesh-tanna/websocket-example

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *