gpt4 book ai didi

tcp - 如何知道 TCP 连接在 net 包中关闭?

转载 作者:IT老高 更新时间:2023-10-28 12:58:44 25 4
gpt4 key购买 nike

我正在实现一个小型 TCP 服务器。我如何知道我的一位客户是否已关闭?我应该尝试读取或写入并检查 err 是否为零?

最佳答案

那个线程“Best way to reliably detect that a TCP connection is closed”,使用 net.Conn 表示 'c'(也可以在 utils/ping.golocale-backend/server.gomany 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 :

In go 1.7+, zero byte reads return immediately and will never return an error.
You must read at least one byte.

commit 5bcdd63go issue 15735

net: don't return io.EOF from zero byte reads

关于tcp - 如何知道 TCP 连接在 net 包中关闭?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12741386/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com