Why do we use WebSockets when AJAX can do the work?
There are a few reasons:
Bi-directional communication.If your service is real-time you will typically not want to make a request and wait for a response; you want a response whenever the server is ready to send one. This isn’t possible with AJAX.
Less server overhead. The alternative to WebSockets are HTTP polling techniques (short- or long-polling) or Server Sent Events. Polling techniques are often inefficient or have a larger server burden than WebSockets. Server Sent Events aren’t standardized across browsers.
Smaller request frames. While less of a problem if you’re using HTTP/2, a lot of HTTP requests come with a lot of overhead that you likely don’t want/need for standard requests. Websockets use much smaller frames for communication, resulting in slightly faster communication.