本篇文章給大家?guī)?lái)了關(guān)于Go的相關(guān)知識(shí),其中主要跟大家聊一聊Go用什么方式實(shí)現(xiàn)SSE,以及需要注意的事項(xiàng),感興趣的朋友下面一起來(lái)看一下吧,希望對(duì)大家有幫助。
一、服務(wù)端代碼
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): // 返回?cái)?shù)據(jù)包含id、event(非必須)、data,結(jié)尾必須使用nn fmt.Fprintf(rw, "id: %dnevent: ping ndata: %dnn", 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) }
登錄后復(fù)制
二、客戶端代碼
const source = new EventSource('http://127.0.0.1:8080/sse'); source.onopen = () => { console.log('鏈接成功'); }; source.addEventListener("ping",function(res){ console.log('獲得數(shù)據(jù):' + res.data); }) source.onerror = (err) => { console.log(err); };
登錄后復(fù)制
三、注意事項(xiàng)(重要)
如果服務(wù)器端提供了event
參數(shù)(完整的消息包含id、data、event),那么客戶端就需要使用addEventListener
顯式監(jiān)聽(tīng)這個(gè)事件,才會(huì)正常獲取消息,否則事件不會(huì)觸發(fā)。如果服務(wù)器端沒(méi)有提供event
參數(shù),只有id、data
等,可以使用onmessage
回調(diào)監(jiān)聽(tīng)消息:
場(chǎng)景一:服務(wù)器有event
參數(shù),并且定義了一個(gè)叫ping
的具體事件
const source = new EventSource('http://127.0.0.1:8080/sse'); source.onopen = () => { console.log('鏈接成功'); }; source.addEventListener("ping",function(res){ console.log('獲得的數(shù)據(jù)是:' + res.data); }) source.onerror = (err) => { console.log(err); };
登錄后復(fù)制
場(chǎng)景二:服務(wù)器返回的數(shù)據(jù)不包含event
const source = new EventSource('http://127.0.0.1:8080/sse'); source.onopen = () => { console.log('鏈接成功'); }; source.onmessage(function(res){ console.log('獲得的數(shù)據(jù)是:' + res.data); }) source.onerror = (err) => { console.log(err); };
登錄后復(fù)制
【推薦學(xué)習(xí):go視頻教程】