在go语言中实现SSE方式、场景及注意事项
Go  /  管理员 发布于 2年前   1511
sse简单的来说就是服务器主动向客户端推送数据的一种技术,它是单向的,也就是说客户端是不能向服务器发送数据的。sse适用于消息推送,监控等只需要服务器推送数据的场景中,下面是使用go来实现一下sse方式。
示例代码:
1.服务端代码
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)
}
2.客服端代码
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显式监听这个事件,才会正常获取消息,否则事件不会触发。
如果服务器端没有提供 event 参数,只有 id、data 等,
可以使用onmessage回调监听消息:
场景一:
服务器有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);
};
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号