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?

net.Conncutils/ping.golocale-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 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屋!