Go如何实现SSE
本篇内容主要讲解“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,结尾必须使用
fmt.Fprintf(rw, "id: %d
event: ping
data: %d
", 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
显式监听这个事件,才会正常获取消息,否则事件不会触发。如果服务器端没有提供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);
};
相关内容
这些是最新的
热门排行
- THINKPHP5+GatewayWorker+Workerman 开发在线客服系统
- 在手机浏览器网页中点击链接跳转到微信界面的方法
- 尊云网站目录系统 ThinkPHP5网站分类目录程序 v2.2.221011
- CentOS 7安装shadowsock(一键安装脚本)
- AdminTemplate 基于LayUI 2.4.5实现的网站后台管理模板
- 用NW.js(node-webkit)开发多平台的桌面客户端
- PHP生成随机昵称/用户名
- THINKPHP5网站分类目录程序 尊云网站目录系统
- 织梦(DEDECMS)微信支付接口 微信插件
- 基于LayUI开发的 网站后台管理模板 BeginnerAdmin
- 响应式后台网站模板 - AMA.ADMIN
- layuiAdmin后台管理模板 Iframe版
- LayUI 1.0.9 升级 至 LayUI 2.1.4 方法
- 简洁清爽的会员中心模板
- jQuery幸运大转盘抽奖活动代码