I recently made an example on how to do websocket communication between a server and a client, where i pushed messages from the server to a client. In this post I will write a little about how websockets are different from normal HTTP communication and some advantages of them. In the title I have written HTTP/REST, this is due to many saying REST when they actually just mean HTTP communication.
HTTP is a stateless protocol. You make one request and you get one response. After this the communication ends and the client and the server forgets about one another. Cookies make it possible for the client to keep some state, so that the server may recognize the client - if you wonder how "sessions" are kept.
A simple get request using HTTP could look like the following:
With websockets the connection stays open and it is not just one request response call. First an initial HTTP request is made from the client asking to upgrade to websockets. The server accepts this request by returning a 101 "switching protocols" HTTP status code and then the bi-directional communication is established. The server and client can now exchange multiple messages, these messages can go both ways if needed, this will look like the below:
When using websockets the connection stays open until either the client or the server sends a message to close it. Which is why the close message arrow above points in both directions.
Comparing websockets and HTTP it could be said the HTTP requests are more simple than using web sockets. However they are also limited, as it is a one-way form of communication (request / response).
HTTP has an overhead in the form of headers for every request. Whereas websockets only have this for the initial request (there is some overhead in the messages, but it is minimal). Websocket messages are therefore smaller if you send more than one message. There is something that websockets can do that normal HTTP communication cannot and that is bi-directional traffic. Sending messages back and forth. If you have an application where the client needs continuous updates from the server, then websockets would be the way to go. This has often been implemented by using long-polling - keeping the request open by waiting to respond. Which seems like an improper use of the HTTP protocol.
Wrapping it up
Should you implement websockets everywhere? No, I do not think so. HTTP is still simpler in many ways and leveraging the built-in cache speeds things up. However if you are building a rich application where several messages are exchanged between the client and server, websockets would be a great fit. This is the use case for websockets in my mind.
This was my post on websockets vs HTTP, please let me know what you think in the comments down below :)