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

Eventsource golang:如何检测客户端断开?,go,server-sent-events,Go,Server Sent Events,我正在开发基于Twitter标签的聊天室,带有服务器发送的事件和软件包 我有一个关于断开客户端连接的问题。我运行goroutine向客户端发送消息,但是当客户端断开连接时,goroutine仍然运行 我不知道如何在服务器端检测到客户端已断开连接 func (sh StreamHandler) ServeHTTP(resp http.ResponseWriter, req *http.Request) { es := eventsource.New( &event

我正在开发基于Twitter标签的聊天室,带有服务器发送的事件和软件包

我有一个关于断开客户端连接的问题。我运行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))
        }
    }()

}

您可以检查ConsumerCount():

有点老套,但似乎管用

你最好使用一个不同的软件包或滚动你自己的软件包,这样你就可以更好地控制你的goroutine的生命周期。您可以在
.Write
(此软件包未公开)上检测到关闭的连接

如果需要,这里有一个TCP中的聊天服务器示例:。 还有一个视频教程

同样的基本模式也适用于SSE。

您可以使用它来了解底层http连接是否已关闭。比如:

notify := w.(http.CloseNotifier).CloseNotify()
go func() {
    <-notify
    // connection close, do cleanup, etc.
}()
notify:=w.(http.closenotifyer.CloseNotify())
go func(){
从2018年12月起,推荐的解决方案是使用
请求
上下文。以下内容适用于我:

done := make(chan bool)
go func() {
        <-req.Context().Done()
        done <- true
}()
<-done
done:=make(chan bool)
go func(){

谢谢你的回答。我的问题是,我使用的软件包没有建议使用ConsumerCount()函数。你有没有一个完整的例子能与最初的问题相吻合,因为我无法实现这个功能?谢谢。@anderspitman有没有办法用这个区分优雅的客户端断开和突然的客户端断开?@ymerej我不知道。检测TCP断开实际上可能相当棘手。不需要
done
频道-只需使用

done := make(chan bool)
go func() {
        <-req.Context().Done()
        done <- true
}()
<-done