How to know TCP connection is closed in Golang net

2019-01-20 23:46发布

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?

标签: tcp go
3条回答
做个烂人
2楼-- · 2019-01-20 23:54

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() {
  ...
查看更多
Root(大扎)
3楼-- · 2019-01-21 00:04
        _, err := conn.Read(make([]byte, 0))
        if err!=io.EOF{
            // this connection is invalid
            logger.W("conn closed....",err)

        }else{
            byt, _:= ioutil.ReadAll(conn);
        }
查看更多
Root(大扎)
4楼-- · 2019-01-21 00:11

Just try to read from it, and it will throw an error if it's closed. Handle gracefully if you wish!

For risk of giving away too much:

func Read(c *net.Conn, buffer []byte) bool {
    bytesRead, err := c.Read(buffer)
    if err != nil {
        c.Close()
        log.Println(err)
        return false
    }
    log.Println("Read ", bytesRead, " bytes")
    return true
}

Here is a nice introduction to using the net package to make a small TCP "chat server":

"Golang Away: TCP Chat Server"

查看更多
登录 后发表回答