猿问

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

我正在开发基于 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))

        }

    }()


}


MM们
浏览 770回答 3
3回答

梵蒂冈之花

截至 2018 年 12 月,显然 CloseNotifier 已弃用。推荐的解决方案是使用RequestContext。以下对我有用:done := make(chan bool)go func() {&nbsp; &nbsp; &nbsp; &nbsp; <-req.Context().Done()&nbsp; &nbsp; &nbsp; &nbsp; done <- true}()<-done

暮色呼如

您可以使用CloseNotifier来让您知道基础 http 连接是否已关闭。喜欢:notify := w.(http.CloseNotifier).CloseNotify()go func() {&nbsp; &nbsp; <-notify&nbsp; &nbsp; // connection close, do cleanup, etc.}()HTH
随时随地看视频慕课网APP

相关分类

Go
我要回答