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 of WebSocket?

2025-02-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

What is the principle of WebSocket? aiming at this problem, this article introduces the corresponding analysis and solution in detail, hoping to help more partners who want to solve this problem to find a more simple and feasible way.

Concept and principle

WebSocket protocol, like HTTP protocol, is at the top of the ISO seven-layer model-the application layer. WebSocket allows the server to actively push data to the client. In the WebSocket protocol, the client browser and the server only need to complete a handshake to create a persistent connection and carry out two-way data transmission between the browser and the server-full-duplex communication.

Comparison of HTTP and WebSocket connection lifecycles:

The WebSocket protocol establishes the transport layer TCP connection through the HTTP protocol.

Web Socket request header field:

Upgrade http protocol to websocket protocol through the Connection:upgrade and upgrade:websocket fields, so the Connection and Upgrade in the request header indicate that the client initiates a WebSocket request

At the same time, there is a Sec-WebSocket-Version field in the request header indicating the protocol version number used by the client, and the server will confirm whether the version number is supported. If so, the response of the server will not have this field. If not, there will be this field in the response field, which corresponds to the version number supported by the server.

Sec-WebSocket-Key is a Base64 code value that is randomly generated by the browser and is used to upgrade request. When the server gets this code value, it will upgrade the http protocol to websocket protocol.

Sec-WebSocket-Extensions represents the protocol-level extension that the client wants to express

Web Socket response header field:

HTTP/1.1 101Switching procotols is a switching protocol. The WebSocket protocol establishes a TCP connection at the transport layer through the HTTP protocol.

Connection and Upgrade, same as request field

Sec-WebSocket-Accept: indicates that the server accepts the request from the client, which is calculated by Sec-Websocket-Key. * * the method of calculation is: * * connect Sec-WebSocket-Key and 258EAFA5-E941-47DA-95CA-C5AB0DC85B11 in the request header, and then take the hash value from SHA-1 to get a 20-bit result, and then convert the result with base64 coding.

Advantages and disadvantages

Advantages:

Support two-way communication, more real-time

The data format is lighter, the performance overhead is low, and the communication is efficient; because the http protocol carries a complete header every time, but after the connection is established, websocket only needs to carry a header of 2-10 bytes from the server to the client, and only 2-10 bytes of headers and 4-byte masks from the client to the server

Support extension, users can extend the protocol or implement custom sub-protocols (such as supporting custom compression algorithm, etc.). The compression algorithm of pied piper in Silicon Valley of American TV series is applied to live broadcast technology.

Disadvantages:

A small number of browsers may not support it, and there are differences in the degree and manner of browser support.

Long connection requires higher code stability of back-end business, and the back-end push function is relatively complex.

In the mature HTTP ecology, there are a large number of components that can be reused, and there are few WebSocket.

Application scenarios:

Instant chat messaging, website message notification

Online collaborative editing, such as Tencent documents

Multi-player online games, video barrage, real-time quotes from stock funds

Application

Business scenario: realize the private message function of the website

Method 1. Use AJAX to poll

Analysis of this way: you can set the request interval is very short (such as 200ms), so that users basically do not feel the delay, can complete the function, but this is a great waste to the network and server, 1. A large number of HTTP requests and responses, each time through the TCP three-way handshake to establish a connection and then return; 2. Even if there is no message, it is necessary to send the request, and both the back-end Web server and the WSGI server have to deal with it. If the number of users is large, the defect of this method will be very obvious.

Method 2. Use WebSocket to establish a connection

Analyze this way: you only need to establish a connection once, and the front end can push to the back end, and the back end can also push to the front end, and only when there is a message, it will not be pushed, and the first byte of the request response is still small. The advantage is very obvious.

Apply this technology in django

Questions to consider:

How to distinguish between routing HTTP requests and WebSocket requests

How to be compatible with django's authentication system (because private messages must be logged in, so authentication is required)

If you receive and push WebSocket messages

How to save and obtain data through ORM

Solution: use django-channels or dwebsocket

Django-channels

What is it: django-channels is a library of bit django that provides asynchronous extensions, usually mainly used to provide WebSocket support and background tasks, because django is a synchronous framework.

Django synchronization framework diagram: a request comes, and the user needs to wait during django processing. The key point is that the nginx will time out.

So, in order to avoid nginx timeout or poor user waiting experience, we can use celery asynchronous task scheduling to asynchronously process time-consuming tasks and let django return a result to nginx and users first.

When the task is done, django cannot actively push the results out, so you need to use channels.

Channels principle:

Request flowchart:

From left to right, the request will be accessed in different directions according to the type.

The overall architecture of channels

This architecture diagram is divided into three layers: 1. Interface Server is responsible for parsing the protocols and distributing different protocols to different Channel. 2. Channel Layer is the second layer. With layer 1 parsing, requests can be divided into http requests and websocket requests. At this time, it is necessary to buffer queuing in different queues of the Channel Layer channel layer, which can be a FIFO queue. Usually, redis is used, and different channels are monitored by different receivers. 3.Consumer consumer layer is used to receive and process channel layer messages.

Channels file and configuration meaning

Asgi.py is a standard interface between network protocol services and Python applications, and can handle a variety of common protocol types, including HTTP, HTTP2 and WebSocket;. If you deploy a network protocol project without websocket, you only need to use nginx+uWSGI+django, because the uWSGI server can recognize wsgi.py;, but if you have a websocket network protocol communication project, you need to use services that meet the asgi interface standards, such as daphne.

Channel_layers needs to be configured in settings.py, similar to a channel in which the sender (producer) sends messages on one end and the consumer (consumer) listens on the other.

Routings.py is equivalent to urls.py in django, writing http routes in urls.py and websocket requests in routings.py, at the same level as the total urls.py

Consumers in consumers.py channels, the equivalent of views.py in django, are created under each app

The difference between WSGI and ASGI

WSGI:Python Web Server Gateway Interface, a simple and general interface between Web servers or frameworks defined for Python

ASGI:Asynchronous Server Gateway Interface, Asynchronous Gateway Service Interface, a direct interface between network protocol services and Python applications, can handle a variety of common protocol types, such as HTTP, HTTP2 and WebSocket

Difference: WSGI is based on HTTP protocol mode and does not support WebSocket, while ASGI is to support the new protocol standard that WSGI does not support in Python, that is, ASGI is an extension of WSGI and can be run asynchronously through asyncio; ASGI can also support chat protocols, loT protocols Internet of things protocol and so on.

The answer to the question about the principle of WebSocket is shared here. I hope the above content can be of some help to you. If you still have a lot of doubts to be solved, you can follow the industry information channel to learn more about it.

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