为了账号安全,请及时绑定邮箱和手机立即绑定

Eventsource golang:如何检测客户端断开连接?

Eventsource golang:如何检测客户端断开连接?

Go
MM们 2021-11-01 16:10:58
我正在开发基于 Twitter 标签和服务器发送事件的聊天室,包https://github.com/antage/eventsource我有关于客户端断开连接的问题。我运行一个 goroutine 向客户端发送消息,但是当客户端断开连接时,goroutine 仍然运行。我不知道如何在服务器端检测客户端断开连接。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 回答

?
梵蒂冈之花

TA贡献1900条经验 获得超5个赞

截至 2018 年 12 月,显然 CloseNotifier 已弃用。推荐的解决方案是使用RequestContext。以下对我有用:


done := make(chan bool)

go func() {

        <-req.Context().Done()

        done <- true

}()

<-done


查看完整回答
反对 回复 2021-11-01
?
暮色呼如

TA贡献1853条经验 获得超9个赞

您可以使用CloseNotifier来让您知道基础 http 连接是否已关闭。喜欢:


notify := w.(http.CloseNotifier).CloseNotify()

go func() {

    <-notify

    // connection close, do cleanup, etc.

}()

HTH


查看完整回答
反对 回复 2021-11-01
  • 3 回答
  • 0 关注
  • 769 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信