Should Put All Requests in a Websocket Connection?
I have a suggestion: When you are entangled in whether to use a certain technology, first check what level the technology solves and what problems, and then examine whether you need to solve such problems. Can save unnecessary entanglement.
So what problem does WebSocket solve? The session management in the traditional HTTP protocol is not perfect. The client must actively initiate a Request request before the server can deliver messages to the client.
If the client submits a time-consuming task to the server, how does the server send a message to the client after it is done? In other words, in some scenarios, the server must ensure that the client is online. The solution is AJAX polling or alive detection. The client sets a timer, and every once in a while the client will initiate an AJAX request to the server, asking whether the server has completed the task, or actively telling the server "I am still online", so as to obtain the data returned by the server in time.
AJAX polling is still useful if there are fewer clients and the server performance is strong enough, but if there are more clients, what if the server has to accept requests from tens of thousands of clients? Not to mention taking up bandwidth, can the server withstand these pressures? If the real-time requirements are high, it means that resources are updated frequently and the amount of data transmitted is large, such as games and web conferences, and the method of conveying messages through AJAX polling cannot be used.
WebSocket solves the two problems mentioned above: it makes up for the defect that the server cannot actively contact the client, and jointly solves the pressure brought by the traditional one-way communication on the server. Another is to solve the problem of real-time communication
The client and the server only need to complete a handshake, and a persistent connection can be created directly between the two, and two-way data transmission can be performed. In this way, even if there is no explicit request from the client, the server can send information to the client, realizing reverse communication.
Although WebSocket also has a certain performance consumption, it is still very cost-effective compared to the consumption of large-scale AJAX polling.
If your business scenario needs to solve the above two problems, then it is recommended to use it, otherwise it is unnecessary, depending on your understanding of the business.