Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is the principle and function of websocket

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "the principle and function of websocket". In the operation process of actual cases, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

First of all, let's take a look at the background of websocket. We know that http series protocols are built on tcp. In theory, it can communicate in both directions. However, before http1.1, the server did not implement push functionality. Each time it is a client request, the server responds. Here's a look at the evolution of the http protocol with respect to request processing.

In http1.0, the life cycle of an http request is that the client initiates the request, the server responds, and the connection is disconnected. However, we know that the shortcomings of tcp protocol are that it takes time for the three-way handshake, coupled with the slow start and other characteristics. If every http request is like this, the efficiency is very low.

http1.1, the default open long connection (client request set keep-alive header), after processing a request, the server will not immediately close the connection, but will wait for a certain time. Close the connection if there is no request. This allows browsers to send requests not only continuously over a tcp connection (the server also limits the number of requests that can be processed over a connection), but many requests at once. This is the pipelining technique of http 1.1. But it also has a problem, because for http-based clients, although he can send out many requests, but when a request for the packet back, he can not tell which request belongs to. Therefore, packets can only be returned in the order requested, which leads to another problem-Head-of-Link Blocking. And although http1.1 supports long connections, it does not support server-side push capabilities. If the server has data to give to the client, it can only wait for the client to pull.

Coming to http2.0, not only the server push, but also the use of frame (iframe), stream (stream) and other technologies to solve the problem of line head blocking, http2.0 in a tcp connection, you can send multiple http requests at the same time, each request is a stream, a stream can be divided into many frames, with the tag number, the server can send back the packet at will, after the client receives, according to the tag, reassembly can be.

While these are some of the http developments regarding requests, websocket provides an alternative solution for server-side push. It is essentially another application layer protocol (websocket protocol) encapsulated on top of tcp protocol. Because it is TCP based, server push is naturally not a problem. But in practice, it doesn't connect directly to a tcp connection and then transmit websocket-based packets over it. It involves a protocol upgrade (swap) process. Let's see how this works.

The client sends a request for protocol upgrade. Add the following http header to the http request

Sec-WebSocket-Extensions: permessage-deflate; client_max_window_bits

Sec-WebSocket-Key: k1kbxGRqGIBD5Y/LdIFwGQ==

Sec-WebSocket-Version: 13

Upgrade: websocket

2 If the server supports the websocket protocol, it will return a status code of 101 indicating that it agrees to the protocol upgrade and supports various configurations (if the server does not support certain features or versions, or tells the client that the client can send the protocol upgrade request again). The service returns an http header such as the following (see websocket protocol).

Connection: Upgrade

Sec-WebSocket-Accept: y73KZR4t+hqD6KKYbkx2tULfBsQ=

Upgrade: websocket

In this way, the upgrade of the protocol is completed, and the subsequent data communication is based on the TCP connection and the data packet encapsulated by the websocket protocol.

Let's see how this works with Wireshark. First we start a server (ip: 192.168.8.226).

var http = require('http');

var fs = require('fs');

const WebSocket = require('ws');

//If you test in the browser console, you can not start http server

const server = http.createServer(options,function(req,res){

res.end(fs.readFileSync(`${__dirname}/websocket.html`));

}).listen(11111);

const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {

ws.on('message', function(message) {

ws.send(message);

});

ws.send('get it');

});

We can test directly in the browser console

var ws = new WebSocket("ws://192.168.8.226:11111");

//connect and execute

ws.send(11)

This time, we look at wireshark's bag.

First look at the first three records, this is the tcp three-way handshake packet. We know all about this, so we don't show it. Then look at the fourth record. After expansion, it is as follows.

We see that after establishing the tcp connection, the browser sends an http request with several websocket packets. Then look at the one below.

The service returned an agreement to upgrade or swap. From the server code we see that we push a get it string to the browser when establishing the connection. Keep looking at the records above.

This is the websocket-based packet pushed by the server to the browser. For details on what each field means, refer to the websocket protocol. Moving on to the next entry is a tcp ack for packets pushed by the server. Finally, we can look at the last three records that say keep-alive. This is the TCP layer keep-alive mentioned in the previous article. Because we haven't been transmitting data, the tcp layer sends probes intermittently. We can look at the structure of the probe packet.

There's one byte of probe data. What if we send a packet to the server?

The three pieces of data on the white background were the data sent by the browser to the server and the data pushed back by the server. TCP's ACK. We found that when the server pushed to the browser, the browser would send ack, but when the browser sent to the server, the server did not seem to return ack. Below we see why. First let's look at packets sent by browsers.

Then look at the packets the server pushes to the browser.

We found that tcp pushed messages with ack. instead of sending two tcp packets. This is the TCP mechanism. TCP does not send ack for every packet, it accumulates acknowledgements (ack) to reduce the number of packets in the network, but it also needs to ensure that it replies ack as soon as possible, otherwise it will cause the client to trigger timeout retransmission. When does tcp send an acknowledgement? For example, when data needs to be sent, or no data packets are received for more than a certain period of time, or the cumulative number of acknowledgements reaches a threshold. Now that we've studied tcp, we might as well study it a little more. Let's see what happens if we shut down the server at this time.

The server sends a reset packet to the browser telling it to disconnect. Go ahead, what if the browser itself calls close to close the connection?

We see that websocket first sends a FIN packet to the server, and then the server returns a FIN packet before the actual four-wave process begins. And the first fin packet of the four waves is from the server.

Let's take a look at the secure version of websocket. We started an https server.

var https = require('https');

var fs = require('fs');

const WebSocket = require('ws');

var options = {

key: fs.readFileSync('./ server-key.pem'),

ca: [fs.readFileSync('./ ca-cert.pem')],

cert: fs.readFileSync('./ server-cert.pem')

};

const server = https.createServer(options,function(req,res){

res.end(fs.readFileSync(`${__dirname}/websocket.html`));

}).listen(11111);

const wss = new WebSocket.Server({ server });

wss.on('connection', function connection(ws) {

ws.on('message', function(message) {

ws.send(message);

});

});

It is then executed in the browser console.

var ws = new WebSocket("wss://192.168.8.226:11111");

ws.sned(11);

Let's look at Wireshark.

First establish tcp connection, then establish tls connection. Subsequent data communications can be based on encryption. No more repetition. Later analysis of the tls protocol will be done.

After a series of analysis, we should have a better understanding of the websocket protocol, and finally a point about websocket. We found that the duration of the websocket connection is tcp dependent if there is no communication over the websocket connection. Because we found that the tcp layer sends probes all the time. When the threshold is reached, the connection is disconnected. So if we want to maintain a websocket connection, we need to send our own heartbeat packets, such as ping, pong.

Summary: this article analyzes the basic principles of websocket, but does not involve the content of the protocol, if you need to understand the content of the protocol, you can refer to the rfc documentation.

"Websocket principle and what is the role" of the content introduced here, thank you for reading. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report