• Go SSE Demo


    1. package main
    2. import (
    3. "fmt"
    4. "github.com/r3labs/sse/v2"
    5. "gopkg.in/antage/eventsource.v1"
    6. "log"
    7. "net/http"
    8. "sync"
    9. "time"
    10. )
    11. func testServer() {
    12. es := eventsource.New(nil, nil)
    13. defer es.Close()
    14. http.Handle("/", http.FileServer(http.Dir("./")))
    15. http.Handle("/events", es)
    16. go func() {
    17. for {
    18. //2秒发送一条当前时间消息,并打印对应客户端数量
    19. es.SendEventMessage(fmt.Sprintf("hello, now is: %s", time.Now()), "", "")
    20. log.Printf("Hello has been sent (consumers: %d)", es.ConsumersCount())
    21. time.Sleep(2 * time.Second)
    22. }
    23. //log.Printf("ES Server Close")
    24. //es.Close()
    25. }()
    26. log.Println("Open URL http://127.0.0.1:9990/1.html in your browser.")
    27. err := http.ListenAndServe(":9990", nil)
    28. if err != nil {
    29. log.Fatal(err)
    30. }
    31. }
    32. func testClient() {
    33. client := sse.NewClient("http://127.0.0.1:9990/events")
    34. //proxyUrl, _ := url.Parse("http://127.0.0.1:9934")
    35. //client.Connection.Transport = &http.Transport{
    36. // TLSClientConfig: &tls.Config{
    37. // InsecureSkipVerify: true,
    38. // },
    39. // Proxy: http.ProxyURL(proxyUrl),
    40. //}
    41. fmt.Println("开始订阅")
    42. client.Subscribe("messages", func(msg *sse.Event) {
    43. // Got some data!
    44. v := string(msg.Data)
    45. fmt.Println("收到消息:" + v)
    46. })
    47. }
    48. func main() {
    49. wg := sync.WaitGroup{}
    50. wg.Add(1)
    51. go testServer()
    52. go testClient()
    53. wg.Wait()
    54. }

    html端 1.html

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <title>SSE test</title>
    5. <script type="text/javascript">
    6. window.addEventListener("DOMContentLoaded", function () {
    7. var evsrc = new EventSource("http://127.0.0.1:9990/events");
    8. var msgEvent = function (ev) {
    9. document.getElementById("log")
    10. .insertAdjacentHTML("beforeend", "
    11. " + ev.data + "
    12. ");
  • }
  • 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>
  • 网页端效果

  • 相关阅读:
    06.K8S常用命令
    JAVA【设计模式】外观模式
    【python数据分析刷题】-N08.排序&函数
    【kali-信息收集】(1.4)识别活跃的主机/查看打开的端口:Nmap(网络映射器工具)
    2019年亚太杯APMCM数学建模大赛A题基于图像分析的二氧化硅熔化表示模型求解全过程文档及程序
    U盘无法正常格式化?教你一个强力的办法
    除了http和https以外的协议
    【wpf】ListView 和 ItemsControl 的一点区别
    牛客刷题系列之进阶版(组队竞赛,排序子序列,倒置字符串, 删除公共字符,修理牧场)
    Java入门------数组
  • 原文地址:https://blog.csdn.net/HeroRazor/article/details/136305470