go
package main
import (
"fmt"
"gopkg.in/antage/eventsource.v1"
"log"
"net/http"
"time"
)
func main() {
es := eventsource.New(nil, nil)
defer es.Close()
http.Handle("/", http.FileServer(http.Dir("./")))
http.Handle("/events", es)
go func() {
for {
// 每2秒发送一条当前时间消息,并打印对应客户端数量
//自定义event,例如拼接上用户id,可以给用户单独推送
es.SendEventMessage(fmt.Sprintf("hello, 现在的时间是: %s", time.Now()), "abc", "")
//默认的event是message是可以不写的
//es.SendEventMessage(fmt.Sprintf("hello, 现在的时间是: %s", time.Now()), "", "")
log.Printf("在线人数: %d", es.ConsumersCount())
time.Sleep(2 * time.Second)
}
}()
err := http.ListenAndServe(":8080", nil)
if err != nil {
log.Fatal(err)
}
}
html
<!DOCTYPE html>
<html>
<head>
<title>SSE test</title>
<script type="text/javascript">
window.addEventListener("DOMContentLoaded", function () {
var evsrc = new EventSource("http://localhost:8080/events");
var msgEvent = function (ev) {
document.getElementById("log")
.insertAdjacentHTML("beforeend", "<li>" + ev.data + "</li>");
}
var msgEvent2 = function (ev) {
document.getElementById("log")
.insertAdjacentHTML("beforeend", "<li>" + ev.data + "-event-abc" + "</li>");
}
//evsrc.onmessage = msgEvent;
//evsrc.addEventListener("message", msgEvent) //默认就是message,也可以自定义event
evsrc.addEventListener("abc", msgEvent2)
evsrc.onerror = function (ev) {
console.log("readyState = " + ev.currentTarget.readyState);
}
})
</script>
</head>
<body>
<h1>SSE测试</h1>
<div>
<ul id="log">
</ul>
</div>
</body>
</html>
效果