NET包中TCP连接是怎么关闭的? [英] How to know TCP connection is closed in net package?
问题描述
我正在实现一个小型TCP服务器.我怎么知道我的一位客户是否关门?我是否应该尝试读取或写入并检查err
是否为零?
I'm implementing a small TCP server. How do I know if one of my clients closed? Should I just try to read or write and check if err
is nil?
推荐答案
该线程"c使用net.Conn
(另请参见 utils/ping.go
或许多其他实例):
That thread "Best way to reliably detect that a TCP connection is closed", using net.Conn
for 'c
' (also seen in utils/ping.go
or locale-backend/server.go
or many other instances):
one := make([]byte, 1)
c.SetReadDeadline(time.Now())
if _, err := c.Read(one); err == io.EOF {
l.Printf(logger.LevelDebug, "%s detected closed LAN connection", id)
c.Close()
c = nil
} else {
var zero time.Time
c.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
}
要检测超时,建议:
if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
...
更新2019: tuxedo25 提到
Update 2019: tuxedo25 mentions in the comments:
在1.7+中,零字节读取立即返回,并且永远不会返回错误.
您必须至少读取一个字节.
In go 1.7+, zero byte reads return immediately and will never return an error.
You must read at least one byte.
请参见提交5bcdd63 和
这篇关于NET包中TCP连接是怎么关闭的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
net
:不要从零字节读取中返回io.EOF
net
: don't return io.EOF
from zero byte reads