Why should you care About Sockets?

Why should you care About Sockets?

Before diving into Sockets Lets Understand, Why do we need it in the first place, So the Protocol, We generally use is HTTP. The issue with HTTP is you can only make unidirectional where client sends the request and the server sends the responses to it and the connection gets terminated. Which is great but in certain use cases, It doesn't make sense to connect again and again to fetch data.

HTTP is stateless protocol runs on the top of TCP which is a connection-oriented protocol it guarantees the delivery of data packet transfer using the three-way handshaking methods and re-transmit the lost packets.

Consider a Situation, Where You want to implement a chat system Every time someone sends a message a Web Hook(A external or internal service which checks incoming requests and Pings the receiver about its existence ) is fired from sender and that makes Request to receiver to Render the whole component again to get a new message, What web sockets is achieving is Direct communication between two Parties, The issue in first approach is we are building connection every time we want to send a message by sent. And in the second one we just keeping connection alive and sending, receiving messages as we they are sent

Web Socket is bidirectional, a full-duplex protocol that is used in the same scenario of client-server communication, unlike HTTP it starts from ws:// or wss://. It is a stateful protocol, which means the connection between client and server will keep alive until it is terminated by either party (client or server). after closing the connection by either of the client and server, the connection is terminated from both the end.

So far you might think, The Problems is solved we are using Sockets, But that's not the case Sockets are a great concept in themselves, It turns out that sockets themselves are not enough to get things done. What we do instead is use a combination of Http Polling and Sockets to get best results, This approach is used in Sockets.io Which is a very popular library to achieve Realtime communication

Http Polling is a process where client sends a request and the server hangs on to the particular request until there is a new data to be sent

Socket.io needs a server side installation and a client side installation to work.

All events are defined in server side and client side sends and receives data from socket server as the communication happens

You can read more about socket.io works here

https://socket.io/docs/v4/how-it-works

You can follow these Blogs get yourself started in Sokets

https://socket.io/get-started/chat

https://medium.com/swlh/chat-rooms-with-socket-io-25e9d1a05947