WebSockets

WebSockets is a relatively new technology which enables full-duplex communication in web sites or web applications. A standard web application uses the HTTP protocol which is a half-duplex communication protocol. The server is always in listen mode and serves incoming requests from clients. In the conventional HTTP protocol there is no way for the server to directly send data to the clients. In order to update the client view in the browser, the client should continuously ask the server and get the new updates if there are any. This method is called polling the server. Polling is normally done using a JavaScript timer which regularly sends Ajax requests to the server. If there are any new updates the data is sent back to the client.

There are some disadvantages to using the polling method:

  • Clients should continuously send Ajax requests to the server which means the server needs to handle a huge number of Ajax requests if there are many clients.

  • Updates can only occur when there is an Ajax request. There is no way to update the client asynchronously. For example, if a timer is set to fire every 30 seconds, client updates can only occur at 30-second intervals.

To overcome this limitation, WebSocket technology was introduced about 10 years ago. Actually, WebSocket is not a new protocol in principle — it is essentially another TCP channel opened between client and server. Unlike HTTP, where TCP connections can be temporary, a WebSocket connection is persistent (always open) and ready to send and receive data. The client browser is able to receive messages from the server through a WebSocket connection, enabling the server to send instant messages to clients so polling mechanisms are no longer needed.