instant messaging is real-time voice, text, video and other communication. At present, there are four ways to realize instant messaging: short polling, long polling, SSE and websocket. Next, let's take a brief look in sequence.
(1) Short polling
means sending a request to the server every short time, the server returns the latest data and then the client updates the interface according to the obtained data, thus indirectly realizing instant communication. The advantage of this method is simple, but the disadvantage is that it puts a lot of pressure on the server and wastes bandwidth traffic, but usually the data has not changed.
(2) Long polling
means that the client sends a request to the server, and then the server checks whether the data requested by the client (that is, the data in the server) has changed. If it has changed, it will immediately respond and return, otherwise, keep this link and check the latest data regularly until data update or connection timeout occurs. Therefore, once the client is disconnected, it will send out a request again, which greatly reduces the number of times the client requests the server in the same time. This method has a disadvantage: the long-term connection of the server will consume resources, the order of returning data cannot be guaranteed, and it is difficult to manage and maintain.
(3)SSE
means server push event. In order to solve the problem that the browser can only transmit data to the server in one direction, HTML5 provides a new technology called server push event SSE. SSE technology provides the function of pushing data from the server to the browser in one direction, but with the active request of the browser, it actually realizes the two-way communication between the client and the server.
(4)websocket
In HTML5, websocket technology is provided to strengthen the functions of the Web. It is not only a web communication mode, but also an application layer protocol. It provides native full-duplex cross-domain communication between browser and server. Through the websocket connection established between the browser and the server, data transmission from the client to the server and from the server to the client can be realized at the same time.