You must be aware of web services where you provide a url and when some hit those url they get some data. Now say there is a change in that data and you want to be aware of that change then what will you do. We can use pooling that is keep calling the url and see if the data is changed. Lets learn about web sockets and how they solve the problem caused by pooling.
Lets understand with an example.
Say we have an url
/state which returns
state = false. Now there is another url
/change_state which changes the value of
state = True but it takes some time say around 10 15 sec. Now you want this state change to be shown using
/state url. What will you do?
Yes you will keep calling this url
/state every second to get the state and show the data. This is called pooling. So what is wrong here?
This increases load on your server. If each one using you servers keep calling these url every second the load on server will increase exponentially. Every new user will add 60 RPM(Request Per Minute) to the server. This is huge. You don’t want your servers to be flooded with these requests.
So pooling uses pull mechanism to that if ask the server for the data.
So can we use push mechanism also?
This will save us a lot of requests if the server is able to push the data once it detects the change in state.
Yup thats totally correct. If we use push we can save lot of requests.
WebSockets is an advanced technology that makes it possible to open an interactive communication session between the user’s browser and a server. With this API, you can send messages to a server and receive event-driven responses without having to poll the server for a reply. This is the definition given by mozilla developer network.
In simple words this web socket allows you to send message from server to client and from client to server in both directions.
Lets see how it works.
Web socket provide persistent connection between client and server using which they can send message to each other.
It is created using upgrade header which is included in regular http request something like below
GET ws://127.0.0.1/ HTTP/1.1 Origin: 127.0.0.1 Connection: Upgrade Host: 127.0.0.1 Upgrade: websocket
If Websocket protocol is supported by server then it send a header in response like below
HTTP/1.1 101 WebSocket Protocol Handshake Date: Wed, 26 Sept 2017 09:06:04 GMT Connection: Upgrade Upgrade: WebSocket
This completes the handshake and connection is now web socket connection and you can see send and receive message from and to server.
Follow the below link for the implementation article which came the next day.