WEB SOCKETS
Builds real time features by establishing a two way
connection between client and server.
Imagine an online multiplayer game where the
leaderboard is constantly changing in the server.
What’s the best way to update the player and show
them the leaderboard? We could ask them to refresh
their browser every few minutes to send a new HTTP
request. Or we can use an interval to poll the server
after every few minutes.
But these options aren’t ideal for real time data and
that’s where web sockets come in.
The first time is for the client to send a HTTP request to
the server asking to open the connection. If server
agrees it’ll send a 101 Switching Protocols response at
which point the handshake is complete.
The TCP/IP connection is now open allowing Bi
directional messages to pass between the two parties
with very low latencies. The connection stays open until
one of the party leaves, then the TCP resources can be
unallocated.
REST APIs vs WebSockets
Example- Real time chatting application
Using REST APIs:
Mary’s app will be send a get request to the server
after a set interval in order to receive the message,
therefore there’s a delay. Even if we lower the
interval to one second, that will cause stress to the
database. Remember these are REST or http API
calls so everytime a request is made its gonna hit
ur server, server checks db and returns to the user.
REST or HTTP APIs follow the Request-Response
model. That means John or Mary needs to make a
request to the server to ask for info. Server can
delay its response or respond right away. However
in this model the server cannot be the one to
initiate conversations so it can’t push messages to
the client or broadcast them out.
That’s where WebSockets come in.
Using WebSockets:
Now with WebSockets, on application load, both
John’s and Mary’s application will establish a
connection to the server and this connection tells
the server “Hello I am connected and ready to
receive messages”. Server now knows that John
and Mary are present. Now when John sends a
message to the server, instead of having Mary
send a GET request for information, the server
broadcasts the data directly.
The server now has knowledge who is actually
connected and can pushes messages to both
clients.
It follows a full duplex or bidirectional
communication.
REST is usually a lot easier to set up but
WebSockets are now supported on every major
browser, however there is some extra effort and
different scaling concerns you need to think about
when using WebSockets.