About web sockets(2)
This is a post to learn and share about web sockets.
In the last article, we learned what web sockets are and what their features are. In this article, we’ll look at why we need web sockets in the first place.
Without web sockets, how would we communicate with servers? Without web sockets, web applications typically only have one-way communication using the HTTP protocol. The HTTP protocol works in a one-way fashion, with the client sending requests to the server and the server returning responses to those requests. This means that after the client sends a request, the client only maintains a connection with the server until the server sends a response.
Disadvantages of one-way communication
- It is difficult to send and receive data in real time.
- You need to implement indirect real-time communication using techniques such as periodic polling or long polling. However, these methods are not efficient and have disadvantages such as creating unnecessary load on the server.
Let’s take a quick look at polling and long polling here.
Polling
Polling is when a client sends a request to the server at regular intervals to see if there is any new data. The client requests data from the server at regular intervals, and the server delivers the current state of the data in response to the request. The client then sends another periodic request to the server to get updated data, and so on. The downside of polling is that the periodic requests generate unnecessary traffic. It can be burdensome for both the server and the client, especially if there are only a few data updates, as the requests must be sent over and over again.
Long Polling
Long polling is a way to improve on the disadvantages of polling, where the client sends a request and the server keeps the connection open until new data is ready. When a client sends a request to a server, the server holds the response until new data is available. When the new data is ready, it sends a response to the client. The client can then immediately send another request to get the new data.
Conclusion
WebSockets overcome these limitations of one-way communication and enable real-time, two-way communication. WebSockets are optimized for sending and receiving data in real time because they maintain a continuous connection between the client and server, and both sides can send and receive data. As a result, WebSockets can be used to provide a better user experience and real-time in web applications.
In the next post, we’ll discuss the disadvantages of websockets.