What is a websocket?
Websocket is a fairly new Internet protocol that allows a permanent connection between the client and the server. It allows for asynchronous data exchange without the need to send additional HTTP requests. Similar to the HTTP, it works over the TCP layer and uses the same ports, that is 80 for unencrypted connections and 443 for encrypted connections.
Before we start
In order to understand the principle of websockets, we should first look how the standard client polls the server through the HTTP protocol.
When the client enters our website, he sends a query to the server via the HTTP protocol. The server processes the query data and sends a response to the client. After this process, the connection is closed and it is not possible to send the client more information without re-sending the query to the server.
This solution works well for less interactive applications. For example, an information portal, company website, simple blog, Internet search engine. When we pass between sub pages, we send new queries to the server and in the response we get subsequent pages displayed by our browser.
How can we optimize this process for modern apps?
However, what can we do if we want our application to show user the data in a real time? For example, if our product is a chat, or if we want to display data from the exchange or smog sensors without forcing the customer to refresh the page continuously. We also do not want our servers to be unnecessarily burdened with excessive amounts of queries.
In this case, the websocket protocol helps us. Thanks to it, we can establish a permanent, two-way connection between the client and the server. Establishing such a connection is very simple. A client who wants to use the websocket protocol first sends an HTTP Upgrade request to the server. This is the so-called Handshake. If the server supports websocket, and all data in the first query is correct then a permanent connection is established. It may be interrupted by one of the parties or when an error occurs.
This is how the basic query and response headers look:
GET /ws HTTP/1.1 Host: localhost:8080 Upgrade: websocket Connection: Upgrade Sec-WebSocket-Key: ygMiQFnG/Gs/T6e/cfgGAw== Sec-WebSocket-Version: 13
HTTP/1.1 101 Switching Protocols Upgrade: websocket Connection: Upgrade Sec-WebSocket-Accept: Oe9g6i5Q0f50k+mwOnnCYXnR5Xo=
Currently, web browsers have an embedded API that allows you to use the websocket protocol. We can find out more about him here. There are also many libraries that make work easier and help in handling data that is sent between the client and the server.
If you want to learn more about the possibilities and application of the websocket protocol, I recommend visiting the websites below.