Introduction to WebSockets
Unlike a HTTP protocol in which the client has to request for a connection over TCP each time they want to request some service, in a WebSocket a persistent connection is set up between the client and a server, and the connection is not closed unless the client or the server wants it to.
In a HTTP protocol, the connection is closed after the request of the client has been acknowledged by the server. If a client has to get the latest updates from the server, they have to request for that particular service using various API’s.
On the other hand, since the connection is not lost in a WebSocket connection, any changes or addition of a data to the server is pushed to all the clients that are listening to the Server through a Socket. Also, the WebSocket provides full-duplex communication, i.e. two way communication between the client and the server. These feature of the websocket helps building in real time applications, such as chat applications, gaming applications, stock market chart view, etc.
The data that the client get are real time data. Client do not have to make any additional requests or invoke any remote methods to get the updated data. Server pushes any changes to every client that is listening to it.
Ajax and WebSockets
So, basically Ajax is used to render content on a view dynamically after getting the updated content from the servers. For example, if there is a change in the total number of entries in a model, for example Student, the new entry must be added along with the old entries and displayed on the webpage. The displaying of the new entry can be done without reloading the webpage using Ajax.
So then, what is the difference between Ajax and Websockets?
Ajax is a concept that runs on top of HTTP. And for the rendering of contents dynamically on a web page, Ajax has to make requests to API’s each and every time. So, for example in a chat application, if we wanted to see the latest messages, we could see those messaged dynamically without any reload using Ajax on our web page, but we also would have to send an API request each time we wanted to view the latest messages.
Web Sockets remove this issue, by providing a continuous connection, and pushing the updates on the server to all the clients listening to it.
Just like a HTTP request is represented by a prefix: http:// A WebSocket protocol is represented using: ws://