溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Go如何實現SSE

發(fā)布時間:2023-02-25 09:35:37 來源:億速云 閱讀:120 作者:iii 欄目:編程語言

本篇內容主要講解“Go如何實現SSE”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“Go如何實現SSE”吧!

一、服務端代碼

package main

import (
   "fmt"
   "net/http"
   "time"
)

type SSE struct {
}

func (sse *SSE) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
   flusher, ok := rw.(http.Flusher)
   if !ok {
      http.Error(rw, "Streaming unsupported!", http.StatusInternalServerError)
      return
   }

   rw.Header().Set("Content-Type", "text/event-stream")
   rw.Header().Set("Cache-Control", "no-cache")
   rw.Header().Set("Connection", "keep-alive")
   rw.Header().Set("Access-Control-Allow-Origin", "*")
   for {
      select {
      case <-req.Context().Done():
         fmt.Println("req done...")
         return
      case <-time.After(500 * time.Millisecond):
         // 返回數據包含id、event(非必須)、data,結尾必須使用\n\n
         fmt.Fprintf(rw, "id: %d\nevent: ping \ndata: %d\n\n", time.Now().Unix(), time.Now().Unix())
         flusher.Flush()
      }
   }

}

func SendData(data chan int64) chan int64 {
   for {
      data <- time.Now().Unix()
      time.Sleep(time.Second * time.Duration(2))
   }
}
func main() {
   http.Handle("/sse", &SSE{})
   http.ListenAndServe(":8080", nil)
}

二、客戶端代碼

    const source = new EventSource('http://127.0.0.1:8080/sse');
    source.onopen = () => {
        console.log('鏈接成功');
    };
    source.addEventListener("ping",function(res){
         console.log('獲得數據:' + res.data);
    })
    source.onerror = (err) => {
        console.log(err);
    };

三、注意事項(重要)

如果服務器端提供了event參數(完整的消息包含id、data、event),那么客戶端就需要使用addEventListener 顯式監(jiān)聽這個事件,才會正常獲取消息,否則事件不會觸發(fā)。如果服務器端沒有提供event 參數,只有id、data等,可以使用onmessage回調監(jiān)聽消息:

場景一:服務器有event 參數,并且定義了一個叫ping 的具體事件

const source = new EventSource('http://127.0.0.1:8080/sse');
source.onopen = () => {
    console.log('鏈接成功');
};
source.addEventListener("ping",function(res){
     console.log('獲得的數據是:' + res.data);
})
source.onerror = (err) => {
    console.log(err);
};

場景二:服務器返回的數據不包含event

const source = new EventSource('http://127.0.0.1:8080/sse');
  source.onopen = () => {
      console.log('鏈接成功');
  };
  source.onmessage(function(res){
       console.log('獲得的數據是:' + res.data);
  })
  source.onerror = (err) => {
      console.log(err);
  };

到此,相信大家對“Go如何實現SSE”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續(xù)學習!

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。

AI