Server-Sent 时时推送消息到客户端例子

2014-03-13 15:22  720人阅读  评论 (0)

Server-Sent 时时推送消息到客户端例子

代码

package main

import (
    "io"
    "net/http"
    "log"
    "time"
    "strconv"
)

func IndexServer(w http.ResponseWriter, req *http.Request) {
    html := `<!DOCTYPE html>
<html>
<head>
<title>Server-Sent Events</title>
</head>
<body>
<script>
var es = new EventSource('msg');
es.onopen = function(e) {
    console.log(e.type);
};
es.onerror = function(e) {
    console.log(e.type);
};
es.onmessage = function(e) {
    document.getElementById(e.type).innerText = e.type+": "+e.data;
};

es.addEventListener('myevent', function(e) {
    document.getElementById(e.type).innerHTML = "event: "+e.type+"<br>id: "+e.lastEventId+"<br>data: "+e.data;
});
</script>
<div id="message"></div>
<div>-----------------------------</div>
<div id="myevent"></div>
</body>
</html>
`
    io.WriteString(w, html)
}

func HelloServer(w http.ResponseWriter, req *http.Request) {
    w.Header().Add("Content-Type", "text/event-stream")
    w.WriteHeader(http.StatusOK)

    io.WriteString(w, "retry: 5000\n\n") // 间隔时间 毫秒

    for i:=0; i<10; i++ {
        if i%2 == 0 {
            io.WriteString(w, "data: "+time.Now().Format("2006-01-02 15:04:05")+"\n\n")
        } else {
            io.WriteString(w, "event: myevent\n") // 事件名称
            io.WriteString(w, "id: "+strconv.Itoa(i)+"\n") // 事件id
            io.WriteString(w, "data: "+strconv.Itoa(int(time.Now().Unix()))+"\n\n") // 事件数据
        }
        w.(http.Flusher).Flush()

        time.Sleep(time.Second)
    }
}

func main() {
    http.HandleFunc("/", IndexServer)
    http.HandleFunc("/msg", HelloServer)
    err := http.ListenAndServe(":12345", nil)
    if err != nil {
        log.Fatal("ListenAndServe: ", err)
    }
}