Do you still remember the once popular QQ show chat room? At that time, still in the junior high school, we, QQ is the most common tool for chatting and making friends; The emergence of QQ show chat room broke the limitations of only searching friends according to the conditions, we can enter the chat room at will, online chat. Miss that wearing the most cool and dazzling QQ show of my debut in the chat room, simple ask a: “have GG/MM?”

The birth of the WebSocket

With the development of the Internet, there are all kinds of chat room software online, all kinds of novel play, but can no longer find that kind of pure feeling in those days. Of course, the attraction of chat rooms and video barrages is real-time communication. Low-latency, high-timeliness technologies are needed to achieve applications that resemble real-time interaction.

In the past, many sites used polling to achieve this scenario. That is, every once in a while (such as every 1 second), the browser makes an HTTP request to the server, asking the server if there is any new information, and then the server returns the latest data to the client. This traditional polling mode has an obvious disadvantage, that is, the browser needs to constantly make requests to the server, but HTTP requests contain a long header, the real valid data may only occupy a small part, which obviously wastes a part of the bandwidth resources. Is there a better way?

WebSocket was born. The WebSocket protocol was born in 2008 and became an international standard in 2011, and WebSocket is also part of the HTML 5 specification. WebSocket is a new protocol that uses TCP sockets on Web pages, allowing both parties to establish a connection channel that stays active and is full duplex (two-way communication between both parties). The WebSocket protocol saves server resources and bandwidth better, and enables more real-time communication.

How is WebSocket different from the HTTP protocol?

HTTP vs WebSocket

HTTP protocol is a half-duplex protocol, that is, at the same time can only handle one direction of data transmission, belongs to one-way transmission. The server is not aware of the connection until the client initiates it. A request is made, a response is received, the communication is over, and the client and server “forget about each other.” But now you can keep the client in a certain state through cookies so that the server can recognize the client.

WebSocket protocol is full duplex, the server can take the initiative to send data to the client at any time, can send or receive information in both directions, belongs to two-way transmission. WebSocket establishes a connection through a handshake between the client and server, and the connection remains “open”, not just a request + a response. First, the client makes a request to establish a connection, and if the server accepts the request, two-way communication is established. The server and client can then exchange information until either the client or server sends a message to shut it down.

WebSocket and HTTP are also related, of course. Because WebSocket needs to establish a connection through the 101 status code of the HTTP protocol. To create a WebSocket connection, you make a request through the browser and wait for the server to respond, a process often called a “Handshaking.”

A typical WebSocket handshake request is as follows:

Client request:

GET / HTTP/1.1

Upgrade: websocket

Connection: Upgrade

Host: localhost.com

Origin: http://localhost.com

Sec-WebSocket-Key: aN3cRrW/n8NuIgdhy2VJFX==

Sec-WebSocket-Version: 13

Server response:

HTTP / 1.1 101 Switching separate Protocols

Upgrade: websocket

Connection: Upgrade

Sec-WebSocket-Accept: pFDoeB2FAdLlXgESz0UT2v7hp0s=

Sec-WebSocket-Location: ws://localhost.com/

Field Description:

  • The Connection field must be Upgrade, indicating that the client wants the Connection upgraded.
  • The Upgrade field must be WebSocket to indicate that you want to Upgrade to the WebSocket protocol.
  • The value of sec-websocket-key is a random string, which is used by the server to construct a summary of SHA-1 information. Add “sec-websocket-key” to a special string “258eafa5-e914-47da-95ca-c5ab0dc85b11”, then calculate SHA-1 and Base64 encode it. Returns the result as the value of the “sec-websocket-accept” header and returns it to the client. This minimizes the risk of ordinary HTTP requests being mistaken for WebSocket protocols.
  • The sec-websocket-version field indicates the supported Version of the WebSocket. RFC6455 requires version 13, and previous drafts should be deprecated.
  • Other fields defined in the HTTP protocol, such as cookies, can also be used in WebSocket.

WebSocket uses a WS or WSS uniform identifier, similar to HTTP/HTTPS. WSS represents the use of TLS WebSocket. Such as:

ws://localhost.com/api

wss://securelocalhost.com/api

WebSocket uses the same TCP port as HTTP/HTTPS. By default, the WebSocket protocol uses port 80; When running on TLS, port 443 is used by default.

The advantage of WebSocket

As a “rising star” and now widely used, there is no doubt that WebSocket has many advantages:

– Less waste of resources

After the connection is created, the packet headers transmitted between the server and the client are relatively small. As opposed to an HTTP request carrying a full header every time, the waste of resources is significantly reduced.

– More real-time

Because the WebSocket protocol is full duplex, the server can actively send data to the client at any time. The latency is significantly less than when an HTTP request has to wait for the client to initiate the request before the server can respond.

– Keep the connection long

Unlike HTTP, WebSocket requires a connection to be created first, which makes it a stateful protocol. HTTP requests may need to carry status information (such as authentication, etc.) on each request.

– Better binary support

WebSocket defines binary frames, making it easier to handle binary content than HTTP.

– Better compression

Compared to HTTP compression, WebSocket, with appropriate extension support, can follow the context of the previous content and significantly improve the compression rate when delivering similar data.

How to choose different business scenarios

Compared to WebSocket and HTTP, HTTP requests are arguably simpler than WebSocket, but they have limitations. You can choose a more appropriate protocol for different usage scenarios.

At present, most websites on the Internet are directly loaded pages, in addition to click to load a new page, interactive work is very little. There is no need to maintain a long connection in this scenario, and using WebSocket would be too “clunky”. Most web pages use static resources such as images, JavaScript or CSS files. In order to load faster, these static resources all need to be cached, and they may not be from the same domain name, in which case it is certainly faster and lighter to use HTTP.

The HTTP protocol sends a header once per request, whereas WebSocket carries the header only when the initial request is established (there is, of course, some overhead in passing messages, but it’s small). Therefore, if you want to send multiple messages continuously, using WebSocket is more resource efficient. If you want to develop a program where the client and server interact continuously, WebSockets are the best choice. Such as:

– Socializing and chatting

Social chat tools, websites online consultation window, etc., this kind of chat application is characterized by low latency, high timeliness. It uses WebSocket protocol to realize real-time communication and meet the needs of communication in an efficient way.

– a barrage

When watching a video, bullet screens are indispensable. Excellent comments, funny jokes and real-time interaction between netizens, sometimes bullet screens are the essence of a video. The barrage needs to be displayed in real time. Through the WebSocket protocol, the barrage information sent by the local client can be pushed to the client of other users through the server and displayed in real time.

– Online Education

Online education has developed rapidly in recent years. You can communicate with teachers and classmates in real time without going out. Teachers assign homework, students interact with each other, ask questions from teachers, and so on. Such real-time interactions can be supported by WebSocket protocol.

– Application of location information updates

In the current mobile device real-time location positioning, real-time network data update, the use of HTTP protocol seems a little clumsy, using WebSocket can make the real-time data update faster.

The cloud WebSocket service product breaks through the limitation that the traditional CDN manufacturer can only accelerate the HTTP/HTTPS protocol, integrates the WebSocket protocol with CDN, combines its own technical experience in the CDN industry for many years, and adopts a variety of optimization technologies. For the use of WS/WSS protocol to communicate with customers to provide quality acceleration service, can effectively reduce the delay, improve efficiency. Come and experience first!

Recommended reading

Talking about WebSocket, 3 minutes will give you a complete understanding of it

Why is HTTPS more secure than HTTP