当前位置:网站首页>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 )
 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 :
 Please add a picture description

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 .

原网站

版权声明
本文为[Lattice titanium Engineer]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202200600139828.html