当前位置:网站首页>Cloud native -- websocket of Web real-time communication technology
Cloud native -- websocket of Web real-time communication technology
2022-06-30 03:54:00 【Shiyu Shiba ya】
“ The article is right Websocket Introduced and summarized ( contain python Programming code ).”
Lead to read
- Why introduce Websocket?
- —— Because in HTTP In , The server cannot send a message to the client Take the initiative to push Updated resources
- PS:HTTP/2 Only static resources can be pushed ( Preset resources ), Unable to push real-time updated information
- HTTP—— Connection is established - Client request - Server response ( If there is no request, the server will not respond )
- Websocket—— Implement client - Server two-way peer-to-peer communication ( Both the server and the client can actively send messages )
- Full duplex protocol ( full duplex —— Communication data can be transmitted in both directions at the same time , Half duplex —— Communication data can only be transmitted in one direction at the same time , Simplex —— Communication data can only be transmitted in one direction )
- Websocket—— Full duplex protocol
- Typical applications : Barrage system
Websocket: The host port is occupied for a long time
HTTP request : Listen to the port and transmit information through the port
- Tradition HTTP How to update information :
polling / A long connection
Many websites are trying to implement push technology , The technology used is polling . Polling is done at specific intervals ( As per 1 second ), Issued by the browser to the server HTTP request , The server then returns the latest data to the client's browser . This traditional model brings obvious disadvantages , That is, the browser needs to keep making requests to the server , However HTTP Requests may contain long headers , The amount of data that actually works is probably only a tiny fraction of that , Obviously this will waste a lot of bandwidth and other resources .

Websocket Introduce
Basics
Websocket And HTTP and HTTPS Use the same TCP port , You can bypass most firewalls . By default ,Websocket Agreement to use 80 port ; Running on the TLS When above , By default 443 port .
establish WebSocket Connect
The client browser sends a message to the server HTTP request ( Request containing updated header information )
Server side parsing —— An answer message is generated to indicate that the upgrade is successful
Connection established successfully —— End to end communication —— Until a party initiates a shutdown request
In the handshake ,Websocket Than HTTP One more handshake , Update the information ( Server response status code 101 Express ), As shown in the figure below
Client message :
- Server message :
- Connection You have to set Upgrade, Indicates that the client wants to upgrade the connection .
- Upgrade Field must be set Websocket, I want to upgrade to Websocket agreement .
Origin: For safe use , Prevent cross station attacks , Browsers generally use this to identify the original domain .
Python Websocket build
Server setup code :
import asyncio
import websockets
async def echo(websocket, path):
async for message in websocket:
message = "I got your message: {}".format(message)
await websocket.send(message)
asyncio.get_event_loop().run_until_complete(
websockets.serve(echo, '127.0.0.1', 8766))
asyncio.get_event_loop().run_forever()- Client build code :
import asyncio
import websockets
async def echo(uri):
async with websockets.connect(uri) as websocket:
while True:
message = input("Write down your message:")
await websocket.send(message)
print("<", message)
recv_text = await websocket.recv()
print("> {}".format(recv_text))
asyncio.get_event_loop().run_until_complete(
echo('ws://127.0.0.1:8766'))The client connects to the server , After the server accepts the connection, both parties establish an end-to-end connection TCP Connect , Two way communication can be realized on this connection , After establishing this connection , There is no distinction between client and server between the two sides of communication , What is provided is End-to-end communication .
Websocket VS HTTP
- Websocket Cannot connect through proxy , Must be connected directly
- Websocket After establishment , Both sides of communication can actively communicate at any time
- Websocket After establishment, information is transmitted through data frames , Do not use request - Response structure
- Websocket Data frames are in order
advantage
- Less control overhead . After the connection is established , When data is exchanged between server and client , The packet header used for protocol control is relatively small . Without the extension , For server to client content , This head is only the size of 2 to 10 byte ( Related to packet length ); For client to server content , This head also needs to be added with extra 4 Byte relative to HTTP Request to carry the full head every time , This cost significantly reduces .
- Strong real time : Because the protocol is full duplex , So the server can send data to the client at any time . be relative to HTTP The request needs to wait for the client to send the request to the server to respond , Delays are significantly less ; Even with Comet And so on Long polling Compare , It can also transfer data more than once in a short time .
- Better binary support .Websocket Defined binary frame , relative HTTP, Binary content can be handled more easily .
- Support extended protocols .Websocket Defined extensions , The user can extend the protocol 、 Implement some custom sub protocols . For example, some browsers support compression .
- Stateful protocol ( contrast HTTP No state ). And HTTP Different ,Websocket You need to establish a connection first , After that, some state information can be omitted during communication . and HTTP The request may need to carry status information in each request ( Such as cookies etc. ).
- WebSocket Not limited by browser homology policy
- WebSockets It is suitable for applications with high real-time requirements 、 The chat room 、 Multiplayer game 、 Real time document collaboration, etc
shortcoming
- The long-term maintenance of the server requires high costs
- Under the high concurrency scenario, the requirements for both sides of communication are high
- It occupies multiple process ports and is limited by general browsers ( for example :firefox by 200)
- WebSocket The handshake phase is prone to security problems (Hijacking)
Reference material
https://zh.m.wikipedia.org/zh-hans/WebSocket
http://www.52im.net/thread-1266-1-1.html
Websocket Online testing sites ( Pay attention to the guarantee )
“ Young people are not afraid of the long way ahead , How dare the years be long . Know that there are tigers —— Turn to tiger mountain . The scars and marks of chasing dreams are the unique medals of teenagers .”
——Created By It's feather 18 ya
边栏推荐
- Product thinking - is the future of UAV express worth looking forward to?
- DBT product initial experience
- Implementation of aut, a self-developed transport layer protocol for sound network -- dev for dev column
- . Net 7 JWT configuration is too convenient!
- laravel9本地安裝
- UML图与List集合
- I have published a book, "changing life against the sky - the way for programmers to become gods", which is open source. I have been working for ten years. There are 100 life suggestions from technica
- 第九天 脚本与资源管理
- Mysql性能优化(6):读写分离
- Number of students from junior college to Senior College (III)
猜你喜欢

Mysql性能优化(6):读写分离

SDS understanding in redis

Day 9 script and resource management

GIS related data
![C # [advanced part] C # multithreading](/img/16/2a7c477b4cee32d9ce1e543c9d4c7e.png)
C # [advanced part] C # multithreading

How to use FME to create your own functional software

Geometric objects in shapely

王爽-汇编语言 万字学习总结

学校实训要做一个注册页面,要打开数据库把注册页面输入的内容存进数据库但是

Arrangement of language resources of upgraded version
随机推荐
11: I came out at 11:04 after the interview. What I asked was really too
Arrangement of language resources of upgraded version
About manipulator on Intelligent Vision Group
NER中BiLSTM-CRF解读score_sentence
Tidb 6.0: making Tso more efficient tidb Book rush
【作业】2022.5.25 MySQL 查操作2
C # [advanced chapter] C # anonymous method [lambda expression to be supplemented...]
【笔记】2022.5.27 通过pycharm操作MySQL
A minimalist way to integrate databinding into activity/fragment
使用IDEAL连接数据库,运行出来了 结果显示一些警告,这部分怎么处理
Buffer pool of MySQL notes
[note] on May 27, 2022, MySQL is operated through pychart
【笔记】2022.5.28 从网页获取数据并写入数据库
[operation] write CSV to database on May 28, 2022
Ubuntu20.04 PostgreSQL 14 installation configuration record
【图像融合】基于交叉双边滤波器和加权平均实现多焦点和多光谱图像融合附matlab代码
Redis中的SDS理解
【作业】2022.5.28 将CSV写入数据库
Number of students from junior college to Senior College (4)
【力扣刷题总结】数据库题目按知识点分类总结(持续更新/简单和中等题已完结)