AJAX Over WebSockets
AJAX Over WebSockets
Developers usually pit AJAX and WebSockets against each other, making it an either or selection. We look at how to combine the two and bring peace to the universe.
Join the DZone community and get the full member experience.Join For Free
I have seen so many AJAX vs. WebSockets discussions that I thought it would be cool if one could combine the two of them. I might be biased, but I have always gravitated towards using WebSockets as the preferred communication mechanism. However, since AJAX is so rooted in many web developers, I thought it would be interesting to see if one could implement AJAX on top of WebSockets.
You may think AJAX and REST are the best technologies since sliced bread; however, the entire AJAX protocol can be built using Websockets technology. This makes Websockets literally a superset of AJAX so it may make sense that we use WebSockets as the main communication link.
There are several benefits to running AJAX over WebSockets, such as:
- Less overhead, thus much faster (including less overhead than HTTP/2).
- Much easier to implement stateful services, if needed.
- Both AJAX and asynchronous WebSocket data can be multiplexed over the same connection.
AJAX returns a single response to a single request. However, AJAX is asynchronous; thus, a web front-end can send any number of AJAX requests without having to wait for each response.
WebSockets, on the other hand, can handle multiple bidirectional messages between the browser and the server. There is no correlation between the messages sent in either direction. It is up to the application to interpret and manage these messages. However, implementing AJAX on a WebSocket connection is conceptually very easy:
- The data is encoded as JSON.
- The JSON data is sent to the server over the WebSocket connection.
- The server reconstructs the data from the JSON string.
- The server finds the AJAX service and calls the service.
- Response data from the AJAX service is encoded as JSON.
- The server sends the JSON response data to the browser via the WebSocket connection.
- The AJAX response is managed in the browser.
Figure 1: Three asynchronous in-flight AJAX requests
Each of the asynchronous responses A', B', and C' must trigger the correct response callback function for the request A, B, and C, even if the response messages should be in a different order.
The easiest way to implement the client side AJAX callback handling is to store each callback in an object and give each callback a unique ID. The ID, which can for example be a number, is sent to the server as part of the message. The server side then bundles this ID with the response data.
Opinions expressed by DZone contributors are their own.