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 matlab用simulink求解一个二阶微分方程,要求截图
    • ¥30 matlab解优化问题代码
    • ¥15 写论文,需要数据支撑
    • ¥15 identifier of an instance of 类 was altered from xx to xx错误
    • ¥100 反编译微信小游戏求指导
    • ¥15 docker模式webrtc-streamer 无法播放公网rtsp
    • ¥15 学不会递归,理解不了汉诺塔参数变化
    • ¥15 基于图神经网络的COVID-19药物筛选研究
    • ¥30 软件自定义无线电该怎样使用
    • ¥15 R语言mediation包做中介分析,直接效应和间接效应都很小,为什么?