dongtuoleng8624 2015-08-20 16:27
浏览 499

EventSource Golang:如何检测客户端断开连接?

I'm developing chat rooms based on Twitter hashtag with Server sent events, with the package https://github.com/antage/eventsource

I have a problem concerning the disconnection of the client. I run a goroutine to send messages to the client, but when the client disconnects, the goroutine still runs.

I don't know how to detect on the server side that the client is disconnected.

func (sh StreamHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) {

    es := eventsource.New(
        &eventsource.Settings{
            Timeout:        2 * time.Second,
            CloseOnTimeout: true,
            IdleTimeout:    2 * time.Second,
            Gzip:           true,
        },
        func(req *http.Request) [][]byte {
            return [][]byte{
                []byte("X-Accel-Buffering: no"),
                []byte("Access-Control-Allow-Origin: *"),
            }
        },
    )

    es.ServeHTTP(resp, req)

    go func() {
        var id int
        for {
            id++
            time.Sleep(1 * time.Second)
            es.SendEventMessage("blabla", "message", strconv.Itoa(id))
        }
    }()

}
  • 写回答

3条回答 默认 最新

  • duangenshi9836 2015-08-21 00:54
    关注

    You could check ConsumersCount():

        go func() {
            var id int
            for es.ConsumersCount() > 0 {
                id++
                es.SendEventMessage("blabla", "message", strconv.Itoa(id))
                time.Sleep(1 * time.Second)
            }
            fmt.Println("closed")
        }()
    

    Kinda hacky, but it seems to work.

    You may be better off using a different package or rolling your own so you could have better control over the lifetime of your goroutines. You can detect a closed connection on .Write (which this package isn't exposing).

    If you want here's an example chat server in TCP: chat-server. And a video tutorial to go with it: tutorial.

    The same basic pattern should work for SSE.

    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器