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

本文探讨了在使用Beego框架开发Web应用时,如何处理客户端关闭连接的情况。通过示例代码展示了在服务器端循环中监听客户端是否断开连接,并详细解释了GoLang的CloseNotify方法的工作原理及其在HTTP/1.1和HTTP/2协议下的行为差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


时间: 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 返回一个通道变量, 当客户端关闭的时候,通道可读。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值