当前位置:网站首页>Technology blog | how to communicate using SSE
Technology blog | how to communicate using SSE
2022-06-25 07:48:00 【Lattice titanium Engineer】
How to use SSE communicate
author : The deer is clear and bright , Titanium Front end engineer
Some time ago Tensorbay Dataset management platform In the front-end development process , There needs to be a action Medium activity log Real time output feature, I suddenly came into contact with a new technology , I can't wait to share with you !
It was delayed 2 Less than a month ,SSE It's coming !
WHAT? What is? SSE?
SSE Full name Server-Sent Events, It literally means that the server pushes information to the client .
We know , The communication between client and server is usually through http request , and http The request fails to make the server actively push information .
Except for one case , That is, the client tells the server that the next request is “ Streaming information ”, An easy to understand example is downloading files from a browser , When a download request is made in the client , The client will tell the server to make the next request “ Streaming information ”, The server will send continuous information to the client , The client will not close the connection , Waiting to receive messages .
SSE Is to use such a mechanism , It realizes the function of pushing information from the server to the client .
SSE Sounds and WebSocket It's kind of like , But careful friends can find ,SSE yes One way passage , Only the server can send information to the client , The client triggered for the first time SSE After the request, you can only receive , Can't reply .
The figure below shows SSE General process of ( The author personally copied the works )

HOW?SSE How to use ?
I understand SSE in the future , How do we use it ?
On the client side ,SSE All of the API It's all defined in EventSource In the object !
EventSource It is a network event interface pushed by the server . One EventSource The example will be right HTTP The service opens a persistent connection , With text/event-stream Format to send events , It will remain open until it is asked to close . Once the connection is on , The incoming messages from the server will be distributed to your code in the form of events . If there is an event field in the received message , The event triggered has the same value as the event field . If no event field exists , The generic event is triggered .
Constructors
EventSource()
pc = new EventSource(url, configuration)
url For remote resource location ,configuration Provides options for configuring new connections .
attribute
- EventSource.onerror: It's a event handler, Called when an error occurs
- EventSource.onmessage: It's a event handler, When you receive a message Is called when
- EventSource.onopen: It's a event handler, Called when a link is established
- EventSource.close: If the link exists , Close the connection ,readyState Set as closed
- EventSource.readyState: Returns a read-only value , Get the status of the current link
- EventSource.url: Returns a read-only value , Get the currently linked URL
use SSE Realization action Medium activity log Real time output
I understand SSE In the client side API in the future , Combined with real-time output log The needs of , We can try to use it .
First, analyze the requirements , You need to select a activity When , Render it in real time on the right side of the screen log.
So clearly , We need to prepare the following :
- The most important Server side URL
- Get message After the onmessage Callback
When you're ready , Sort out the logic
We will maintain two in the page state, One is EventSource object , The other one needs to be shown log Content data
const [data, setData] = React.useState<string>(''); const [event, setEvent] = React.useState<any>(null);stay log When the page is rendered, it is created with the back end sse Connect
const newEvent = new EventSourcePolyfill(`urlValue`, { headers });When the backend pushes message When I get back , We change data Value , Realize the effect of real-time output
newEvent.onmessage = (e: any) => { logs = logs.concat(`${ e.data}\n`); setData(logs); }; newEvent.onerror = () => { newEvent.close(); };
A careful friend may notice a detail here !
That's it !
I didn't use the above mentioned EventSource() ah !
It uses a and that seem to be encapsulated EventSource()
Very similar but different EventSourcePolyfill() ah !
Why is this ?!
The answer is
EventSource Incoming is not supported headers, It cannot be transmitted to the server token. So for the need token For this resource , Don't pass on token Equal to driving without a license , Don't give or drop , So I am in the omnipotent gayhub On the survey, we found that EventSourcePolyfill, You can use it ! Pass to ! Server side !token 了 !
The final curl as follows :
curl 'https://gas.fat.graviti.cn/gatewayv2/venom-daemon/v1/activity/83639073cb30496c8a5794e9f9ad9276/logs/?&node_id=wf-i5ruzz-qsclf-1529545071&container=main&follow=true' \
-H 'authority: gas.fat.graviti.cn' \
-H 'sec-ch-ua: " Not;A Brand";v="99", "Google Chrome";v="91", "Chromium";v="91"' \
-H 'accept: text/event-stream' \
-H 'x-token: 7cd82d49be4b468eb746a283121574e9' \
-H 'sec-ch-ua-mobile: ?0' \
-H 'user-agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.114 Safari/537.36' \
-H 'sec-fetch-site: same-origin' \
-H 'sec-fetch-mode: cors' \
-H 'sec-fetch-dest: empty' \
-H 'referer: https://gas.fat.graviti.cn/dataset/5c2d5481/zj_test/actions/wf/i5ruzz-qsclf?tab=log' \
-H 'accept-language: zh-CN,zh;q=0.9,en;q=0.8' \
-H 'cookie: gr_user_id=a7f2dde3-1fb7-4f4e-8ef4-adf94a0f611e; Hm_lvt_88214dfcc23a7cf3e22c61fc2032b3cc=1624525026; _ga=GA1.1.588941179.1620461955; Hm_lpvt_88214dfcc23a7cf3e22c61fc2032b3cc=1625802074; Hm_lvt_16e30fb4f44e9e645bce6c970883ebce=1625197778,1625638587,1625712443,1625802597; _ga_JMKPTKFK1Q=GS1.1.1625824946.4.0.1625824946.0; Hm_lpvt_16e30fb4f44e9e645bce6c970883ebce=1625985701; X-Token=7cd82d49be4b468eb746a283121574e9; 9383fdc1263bf861_gr_last_sent_sid_with_cs1=46cc67df-d7aa-4e46-9d61-75332ce7016c; 9383fdc1263bf861_gr_last_sent_cs1=bf3f0b777057a26f52b661c1f19eaa86; 9383fdc1263bf861_gr_session_id=46cc67df-d7aa-4e46-9d61-75332ce7016c; 9383fdc1263bf861_gr_session_id_46cc67df-d7aa-4e46-9d61-75332ce7016c=true; 9383fdc1263bf861_gr_cs1=bf3f0b777057a26f52b661c1f19eaa86' \
--compressed
The most different thing is here :
-H 'accept: text/event-stream' \
-H 'x-token: 7cd82d49be4b468eb746a283121574e9' \
The renderings are here :
Good. Thank you for your patience , Please point a little love when you pass by ️
See you next time !
【 About lattice titanium 】:
Gewu titanium intelligent technology is positioned as a data platform for machine learning , Committed to AI Developers build the next generation of new infrastructure , Fundamentally change the way it interacts with unstructured data . Through unstructured data management tools TensorBay And the open source dataset community Open Datasets, Help machine learning teams and individuals reduce data acquisition 、 Storage and processing costs , Speed up AI Development and product innovation , Empowering artificial intelligence with thousands of lines and industries 、 Provide a solid foundation for driving industrial upgrading .
边栏推荐
- Domestic MCU perfectly replaces STM chip model of Italy France
- How much do you know about electronic components on PCB?
- 基于激光雷达的林业调查常用术语及含义锦集
- 【深度学习 轻量型backbone】2022 EdgeViTs CVPR
- Sichuan Tuwei ca-if1051 can transceiver has passed aec-q100 grade 1 certification
- 一次弄清楚 Handler 可能导致的内存泄漏和解决办法
- Five causes of PCB board deformation and six solutions 2021-10-08
- NPM install reports an error: gyp err! configure error
- Estimation of dense forest volume based on LIDAR point cloud with few ground points
- “空间转换”显著提升陡崖点云的地面点提取质量
猜你喜欢

Misunderstanding of switching triode

Leetcode daily question - 515 Find the maximum value in each tree row

(tool class) use SecureCRT as the communication medium

OpenCV每日函数 结构分析和形状描述符(8) fitLine函数 拟合直线

Share the process requirements for single-layer flexible circuit board

Understand the reasons for impedance matching of PCB circuit board 2021-10-07

npm install 报错 : gyp ERR! configure error

Summary of small problems in smartbugs installation

Knowledge sharing 𞓜 conventional laminated structure of six layer PCB

Pcb|about FPC reinforcement type
随机推荐
Accès à la boîte aux lettres du nom de domaine Lead à l'étranger
Fairmot yolov5s to onnx
"Spatial transformation" significantly improves the quality of ground point extraction of cliff point cloud
Chuantu microelectronics ca-if1051 can-fd transceiver
Leetcode daily question - 515 Find the maximum value in each tree row
不同路径II[针对DFS的动态规划改进]
如何用svn新建属于自己的分支
WinForm实现窗口始终在顶层
基于地面点稀少的LiDAR点云的茂密森林蓄积量估算
Modular programming of digital light intensity sensor module gy-30 (main chip bh1750fvi) controlled by single chip microcomputer (under continuous updating)
realsense d455 semantic_ Slam implements semantic octree mapping
C#中如何调整图像大小
Mysql面试-执行sql响应比较慢,排查思路。
Runtime - Methods member variable, cache member variable
微信小程序入门记录
“空间转换”显著提升陡崖点云的地面点提取质量
Tips 𞓜 how to clean PCB boards 2021-10-22
Atlassian Confluence 远程代码执行漏洞(CVE-2022-26134漏洞分析与防护
对链表进行插入排序[dummy统一操作+断链核心--被动节点]
One "stone" and two "birds", PCA can effectively improve the dilemma of missing some ground points under the airborne lidar forest