I recently created a chatting application with the intention of having it update live and quickly realized I didn’t know what I needed to make that happen. When I first started looking at WebSockets, they seemed like a very scary thing and I wasn’t sure how to go about implementing them. So I just want to explain what they are and attempt to demystify them here.
A WebSocket is a transfer protocol, similar to HTTP or HTTPS — the two that most people are aware of. So to best understand WebSockets let’s first look at a standard HTTP request. Generally, when you request information from a server it is in the form of HTTP, for example, a GET request that looks something like “http://www.arequesttotheserver.com”. When a GET request is made a TCP connection is made with the server while it retrieves the requested information and after the server sends its response the connection with the server is closed.
The difference in a WebSocket is that when a request is made, for example, a GET request that looks something like “ws://www.arequesttotheserver.com”, a TCP connection is made, AND HELD. This connection is called a TCP handshake and instead of being closed when the server responds, it is left open to continue to send and receive data to and from the server. The TCP handshake is only closed when either the server or client specifically breaks the connection.
The persistent connection means that the client can receive live updates from the server, since every time a change is made on the server that change is pushed to the client. The client can also send data through the connection so other users connected to the server can see changes that our client makes to the server as they happen.
Hopefully, if you were confused about WebSockets this helps simplify some of whats going on behind the scenes!