您的位置:首页 > 编程语言 > Go语言

GoLang 中 当 Client 关闭链接后, Server 如何处理。

2018-01-19 15:15 495 查看
时间: 2018-01-19

最近, 使用 beego 框架开发了一些 Web应用, 

Beego中的 "Serverlet" 基本, 都长类似的样子

// @router /follow [post]
func (ctl *EventController) GetEvents() {
..........

}


有时候,服务的时间, 比较长。 比如这样的:

for {

line, err := rr.ReadBytes('\n')
if err != nil { //if io.EOF == err {
break
}
................
}


服务器端的循环,如何退出?

go func() {
w := ctl.Ctx.ResponseWriter
<-http.CloseNotifier(w).CloseNotify()

ctl.Ctx.ResponseWriter.Flush()
..................
}()


可以用这种办法。

具体 golang 中方法说明如下:

// CloseNotify returns a channel that receives at most a
// single value (true) when the client connection has gone
// away.
//
// CloseNotify may wait to notify until Request.Body has been
// fully read.
//
// After the Handler has returned, there is no guarantee
// that the channel receives a value.
//
// If the protocol is HTTP/1.1 and CloseNotify is called while
// processing an idempotent request (such a GET) while
// HTTP/1.1 pipelining is in use, the arrival of a subsequent
// pipelined request may cause a value to be sent on the
// returned channel. In practice HTTP/1.1 pipelining is not
// enabled in browsers and not seen often in the wild. If this
// is a problem, use HTTP/2 or only use CloseNotify on methods
// such as POST.
CloseNotify() <-chan bool

也就是说, CloseNotify 返回一个通道变量, 当客户端关闭的时候,通道可读。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  golang beego controller
相关文章推荐