Home >Backend Development >Golang >How to Reliably Detect TCP Connection Closure in Go's `net` Package?

How to Reliably Detect TCP Connection Closure in Go's `net` Package?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-19 04:58:16353browse

How to Reliably Detect TCP Connection Closure in Go's `net` Package?

Detecting TCP Connection Closure in 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:

  • SetReadDeadline sets a time beyond which read operations will fail with a timeout error.
  • The < byte 1 is read to test the connection. If it's closed, an End of File (EOF) error is returned.
  • If the read does not return EOF, a new deadline is set to check for timeout in subsequent operations.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn