Introduction
How should the server and the client communicate? Our common method is that the client sends a request to the server, and then the server sends the response back to the client. This approach is relatively simple and the logic is very clear, but in some cases, this method of operation is not easy to use.
For example, some changes on the server side need to be notified to the client, because the client does not know whether the changes on the server side are completed, so it needs to continuously use round robin to check the status of the server. The disadvantage of this approach is that it is too wasteful of resources. If you want good timeliness, you need to continuously reduce the round-robin time interval, resulting in great server pressure and waste of resources.
So is there a good solution?
Since you can't use queries, just change to server push. We know that in HTTP/2, a server push method is provided, but this method is one-way, which means that the interaction between the client and the server cannot be realized on the same TCP connection.
So we need a network protocol capable of two-way interaction, this protocol is WebSocket.
webSocket vs HTTP
webSocket is a two-way communication network protocol based on the underlying TCP protocol. This two-way communication is achieved through a TCP connection. webSocket was released as an IETF standard in 2011 under RFC 6455.
Also as a standard protocol based on TCP protocol, what is the difference between it and HTTP?
If the OSI seven-layer model is used, both are located in the fourth layer of the seven-layer protocol. But the two are two different agreements. In view of the fact that HTTP has become so popular, in order to ensure the versatility of webSocket, webSocket is also compatible with the HTTP protocol. That is to say, where the HTTP protocol can be used, webScoket can also be used.
This is a bit similar to the HTTP3 discussed earlier. Although HTTP3 is a new protocol, in order to ensure its broad application foundation, HTTP3 is still rewritten and built on the existing UDP protocol. The purpose is to be compatible.
In real time, webSocket uses HTTP upgrade header, which is upgraded from HTTP protocol to webSocket protocol.
HTTP upgrade header
What is the HTTP upgrade header?
HTTP upgrade header is an HTTP header introduced in HTTP 1.1. When the client feels that it needs to upgrade the HTTP protocol, it will send an upgrade request to the server, and the server will respond accordingly.
For websocket, after the client establishes a connection with the server, it will first send the Upgrade: WebSocket and Connection: Upgrade headers to the server. After the server receives the client's request, if it supports the webSocket protocol, it will return the same Upgrade: WebSocket and Connection: Upgrade headers to the client. After the client receives the response from the server, it knows that the server supports the websocket protocol, and then can use the WebSocket protocol to send messages.
Advantages of websocket
In fact, we have also mentioned before that, compared to the traditional HTTP pull, webSocket can realize real-time data transmission by means of a TCP connection. It can realize real-time communication between the server and the client while reducing the pressure on the server.
Application of webScoket
WebSocket uses ws and wss as URI markers. Among them, ws means websocket, and wss means WebSocket Secure.
Because usually we use a web browser to communicate with the server. The browser is our web client. For modern browsers, they basically support the WebSocket protocol, so you can use it with confidence and don't worry about protocol compatibility.
For the browser client, a standard browser WebSocket object can be used to communicate with the server. Let’s look at a simple example of a javascript client using webSocket to communicate:
// 使用标准的WebSocket API创建一个socket连接
const socket = new WebSocket('ws://www.flydean.com:8000/webscoket');
// 监听webSocket的open事件
socket.onopen = function () {
setInterval(function() {
if (socket.bufferedAmount == 0)
socket.send(getUpdateData());
}, 50);
};
// 监听接收消息事件
socket.onmessage = function(event) {
handleUpdateData(event.data);
};
// 监听socket关闭事件
socket.onclose = function(event) {
onSocketClose(event);
};
// 监听error事件
socket.onerror = function(event) {
onSocketError(event);
};
The above code is mainly to monitor various socket events and then process them, which is very simple.
Handshake process of websocket
As we mentioned above, websocket is upgraded from HTTP protocol, and the client sends:
Upgrade: websocket
Connection: Upgrade
Go to the server side and upgrade the protocol. Let's give a concrete example:
GET /webscoket HTTP/1.1
Host: www.flydean.com
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Key: x123455688xafe=
Sec-WebSocket-Protocol: chat, superchat
Sec-WebSocket-Version: 13
Origin: http://flydean.com
The return of the corresponding server:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: Qhfsfew12445m=
Sec-WebSocket-Protocol: chat
In the above example, in addition to using the Upgrade header, the client also sends a Sec-WebSocket-Key header to the server. This header contains a random byte encoded in base64. The server will return the hash value of this key and set it in the Sec-WebSocket-Accept header.
This is not for safe operation, but to avoid the last connection cache situation.
WebSocket API
If you want to use WebSocket on the browser side, you need to use the client API, and the most important of the client API is WebSocket.
It provides a functional encapsulation of websocket. Its constructor is like this:
WebSocket(url[, protocols])
The url is the address of the websocket to be connected, so what are the optional protocols? protocols can be passed in a single protocol string or an array of protocol strings. It refers to the sub-protocol implemented by the WebSocket server.
The sub-protocol is a protocol developed on the basis of the WebSocket protocol. It is mainly used for the processing of specific scenarios. It is a stricter specification established on the WebSocket protocol.
For example, when the client requests the server, it puts the corresponding protocol in the Sec-WebSocket-Protocol header:
GET /socket HTTP/1.1
...
Sec-WebSocket-Protocol: soap, wamp
The server will respond according to the supported types, such as:
Sec-WebSocket-Protocol: soap
The WebSocket API has four states, namely:
State definition | Value |
---|---|
WebSocket.CONNECTING | 0 |
WebSocket.OPEN | 1 |
WebSocket.CLOSING | 2 |
WebSocket.CLOSED | 3 |
By calling the close or Send method, the corresponding events will be triggered. The events of the WebSocket API mainly include: close, error, message, and open.
The following is an example of specific use:
// 创建连接
const socket = new WebSocket('ws://localhost:8000');
// 开启连接
socket.addEventListener('open', function (event) {
socket.send('没错,开启了!');
});
// 监听消息
socket.addEventListener('message', function (event) {
console.log('监听到服务器的消息 ', event.data);
});
Summarize
The above is a brief introduction and use of websocket. If you want to know how Websocket performs message transmission, please look forward to my next article.
This article has been included in http://www.flydean.com/06-websocket/
The most popular interpretation, the most profound dry goods, the most concise tutorial, and many tips you don't know are waiting for you to discover!
Welcome to pay attention to my official account: "Program those things", know technology, know you better!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。