Home >Backend Development >Golang >How to Reliably Detect TCP Connection Closure in Go's `net` Package?
In TCP servers, it's crucial to determine when clients have closed connections. This article explores how to effectively detect this in the net package.
The approach suggested in the question, relying on read or write operations with error checking, is not recommended. Instead, a more reliable method is to set read deadlines and check for specific error conditions.
Recommended Approach:
The following code snippet, taken from the "Best way to reliably detect that a TCP connection is closed" thread, demonstrates the recommended approach:
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)) }
Explanation:
Timeout Detection:
For timeout detection, the following code can be used:
if neterr, ok := err.(net.Error); ok & neterr.Timeout() { ... }
This checks if the error is a net.Error, which contains additional information like Timeout().
Updates:
In Go 1.7 and later, zero-byte reads return immediately without an error. Therefore, it's recommended to read at least one byte.
The above is the detailed content of How to Reliably Detect TCP Connection Closure in Go's `net` Package?. For more information, please follow other related articles on the PHP Chinese website!