Home > Backend Development > Golang > How Can I Reliably Detect Closed TCP Connections in Go's `net` Package?

How Can I Reliably Detect Closed TCP Connections in Go's `net` Package?

Mary-Kate Olsen
Release: 2024-12-24 10:39:28
Original
819 people have browsed it

How Can I Reliably Detect Closed TCP Connections in Go's `net` Package?

Monitoring TCP Connection Status in the Net Package

A common task in TCP server implementations is determining when a client connection has been closed. This question explores a reliable method for detecting connection closures in the Go net package.

Checking for Closed Connections

The suggested approach is to attempt both a read and write operation and check if either returns nil error. If both operations succeed, the connection is assumed to be open. However, this method has limitations.

Reliable Detection Using Timeouts

A more reliable solution involves setting a read deadline and attempting a one-byte read. If the read completes with an io.EOF error, the connection is considered closed. To prevent false positives due to slow clients, a non-zero read deadline can be set.

one := make([]byte, 1)
c.SetReadDeadline(time.Now())
if _, err := c.Read(one); err == io.EOF {
  // Connection closed
}
Copy after login

Timeout Detection

If the read timeout expires, the provided error will implement the net.Error interface, and the error's Timeout() method can be used to verify the cause.

if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  // Connection timed out
}
Copy after login

Go 1.7 Considerations

In Go 1.7 , zero-byte reads return immediately without an error. Therefore, ensuring that at least one byte is read is crucial to avoid false positives.

The above is the detailed content of How Can I Reliably Detect Closed TCP Connections in Go's `net` Package?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template