- package main
-
- import (
- "fmt"
- "github.com/r3labs/sse/v2"
- "gopkg.in/antage/eventsource.v1"
- "log"
- "net/http"
- "sync"
- "time"
- )
-
- func testServer() {
- es := eventsource.New(nil, nil)
- defer es.Close()
-
- http.Handle("/", http.FileServer(http.Dir("./")))
- http.Handle("/events", es)
- go func() {
-
- for {
- // 每2秒发送一条当前时间消息,并打印对应客户端数量
- es.SendEventMessage(fmt.Sprintf("hello, now is: %s", time.Now()), "", "")
- log.Printf("Hello has been sent (consumers: %d)", es.ConsumersCount())
- time.Sleep(2 * time.Second)
- }
- //log.Printf("ES Server Close")
- //es.Close()
- }()
-
- log.Println("Open URL http://127.0.0.1:9990/1.html in your browser.")
- err := http.ListenAndServe(":9990", nil)
- if err != nil {
- log.Fatal(err)
- }
- }
-
- func testClient() {
- client := sse.NewClient("http://127.0.0.1:9990/events")
-
- //proxyUrl, _ := url.Parse("http://127.0.0.1:9934")
- //client.Connection.Transport = &http.Transport{
- // TLSClientConfig: &tls.Config{
- // InsecureSkipVerify: true,
- // },
- // Proxy: http.ProxyURL(proxyUrl),
- //}
- fmt.Println("开始订阅")
- client.Subscribe("messages", func(msg *sse.Event) {
- // Got some data!
- v := string(msg.Data)
- fmt.Println("收到消息:" + v)
- })
- }
-
- func main() {
- wg := sync.WaitGroup{}
- wg.Add(1)
-
- go testServer()
- go testClient()
-
- wg.Wait()
- }
html端 1.html
- <!DOCTYPE html>
- <html>
- <head>
- <title>SSE test</title>
- <script type="text/javascript">
- window.addEventListener("DOMContentLoaded", function () {
- var evsrc = new EventSource("http://127.0.0.1:9990/events");
- var msgEvent = function (ev) {
- document.getElementById("log")
- .insertAdjacentHTML("beforeend", "
- "
+ ev.data + ""); - }
- evsrc.onmessage = msgEvent;
- //evsrc.addEventListener("message", msgEvent)
- evsrc.onerror = function (ev) {
- console.log("readyState = " + ev.currentTarget.readyState);
- }
- })
- </script>
- </head>
- <body>
- <h1>SSE test</h1>
- <div>
- <ul id="log">
- </ul>
- </div>
- </body>
- </html>
网页端效果