如何知道net包中的TCP连接已关闭? [英] How to know TCP connection is closed in net package?

查看:16
本文介绍了如何知道net包中的TCP连接已关闭?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实现一个小型 TCP 服务器.我怎么知道我的一位客户是否关门了?我应该尝试读取或写入并检查 err 是否为零?

解决方案

那个帖子 "可靠检测 TCP 连接关闭的最佳方法",使用 net.Conn 表示 'c'(也见于 utils/ping.go<代码>locale-backend/server.go许多其他实例):

one := make([]byte, 1)c.SetReadDeadline(time.Now())如果 _, 错误 := c.Read(one);错误 == io.EOF {l.Printf(logger.LevelDebug, "%s 检测到关闭的 LAN 连接", id)c.关闭()c = 零} 别的 {var 零时间.Timec.SetReadDeadline(time.Now().Add(10 * time.Millisecond))}

为了检测超时,它建议:

if neterr, ok := err.(net.Error);好的&&neterr.Timeout() {...

<小时>

2019 年更新:tuxedo25 提到了 在评论中:

<块引用>

在 go 1.7+ 中,零字节读取立即返回并且永远不会返回错误.
您必须至少读取一个字节.

参见 commit 5bcdd63转到问题 15735

<块引用>

net:不从零字节读取返回io.EOF

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?

解决方案

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))
}

For detecting a timeout, it suggests:

if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  ...


Update 2019: tuxedo25 mentions 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.

See commit 5bcdd63 and go issue 15735

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

这篇关于如何知道net包中的TCP连接已关闭?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆