如何在Golang网络包中关闭TCP连接? [英] How to know TCP connection is closed in Golang net package?

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

问题描述

我是Golang的新手。

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

该线程可靠检测TCP的最佳方式连接已关闭,使用 net.Conn 作为' c '(也见于 utils / ping.go locale-backend / server.go 许多其他实例):

  one:= [] byte {} 
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 0 time.Time
c.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
}


为了检测超时,它建议:

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


I'm new to Golang.

I'm implementing a small TCP server, and 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 := []byte{}
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() {
  ...

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

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