线程"utils/ping.go
158/http://osdir.com/ml/go-language-discuss/2012-08/msg01586.html" rel="noreferrer">Best way to reliably detect that a TCP connection is closed",使用net.Conn
表示"c
"(也可以在utils/ping.go
、locale-backend/server.go
或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个提到in the comments个:
在GO 1.7+中,零字节读取会立即返回,并且永远不会返回错误.
您必须至少读取一个字节.
见commit 5bcdd63和go issue 15735
net
: don't returnio.EOF
from zero byte reads