dongxie2749 2019-03-13 13:03
浏览 157

Golang的SSE延迟

I'm trying to make console using sse that shows client what server is doing. Currently it does what I want except it has a delay (about 2sec). I added http.Flusher but is seems to do absolutely nothing. I call UpdateLogMessage using goroutines: go UpdateLogMessage("Example")

SSE:

type Upl struct {
    log string
}

var Log chan *Upl

func DashboardHandler(w http.ResponseWriter, r *http.Request) {
    f, ok := w.(http.Flusher)
    if !ok {
        fmt.Println("Streaming unsuported")
    }

    w.Header().Set("Content-Type", "text/event-stream")
    w.Header().Set("Cache-Control", "no-cache")
    w.Header().Set("Connection", "keep-alive")

    msg := <-Log
    fmt.Fprintf(w, "data: %v

", msg.log)
    f.Flush()
}

//Updates log message with curent time and message content
func UpdateLogMessage(msg string) {
    curentTime := time.Now().Format("15:04:05")
    ul := fmt.Sprintf("<%v> %v", curentTime, msg)
    up := &Upl{
        log: ul,
    }
    Log <- up
}

func MakeChan() {
    Log = make(chan *Upl)
}

Javascript:

function onLoaded(){
    var source = new EventSource("sse/dashboard")
    var logg = "";
    var currentmsg = "";

    source.onmessage = function (event){
        var dashboard = event.data;
        //If message changed print it to console
        if (dashboard != currentmsg){
            console.log("OnMessage called:");
            console.dir(event);
            currentmsg = dashboard;
            logg += currentmsg + "<br/>";
            console.log(logg);
            document.getElementById("console").innerHTML = logg;
        }
    }
}
  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 shape_predictor_68_face_landmarks.dat
    • ¥15 slam rangenet++配置
    • ¥15 对于相关问题的求解与代码
    • ¥15 ubuntu子系统密码忘记
    • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
    • ¥15 保护模式-系统加载-段寄存器
    • ¥15 电脑桌面设定一个区域禁止鼠标操作
    • ¥15 求NPF226060磁芯的详细资料
    • ¥15 使用R语言marginaleffects包进行边际效应图绘制
    • ¥20 usb设备兼容性问题