Home > Backend Development > Golang > How Can I Reliably Detect TCP Connection Closure in Go?

How Can I Reliably Detect TCP Connection Closure in Go?

Mary-Kate Olsen
Release: 2024-12-16 07:06:10
Original
562 people have browsed it

How Can I Reliably Detect TCP Connection Closure in Go?

Detecting TCP Connection Closure in Go's net Package

When implementing a TCP server, monitoring client connections is crucial. To determine whether a client has closed the connection, it's important to avoid solely relying on read/write operations. Instead, a comprehensive approach is recommended.

Preferred Method:

The thread "Best way to reliably detect that a TCP connection is closed," suggests using a combination of SetReadDeadline() and Read() functions:

one := make([]byte, 1)
c.SetReadDeadline(time.Now())
if _, err := c.Read(one); err == io.EOF {
  // Client has closed the connection
  c.Close()
  c = nil
} else {
  c.SetReadDeadline(time.Now().Add(10 * time.Millisecond))
}
Copy after login

By setting a timeout on the read operation, you can determine whether the connection is closed based on the io.EOF error.

Timeout Detection:

In case you encounter a timeout during the read operation, the Go documentation provides guidance:

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

Updates in Go 1.7 :

It's worth noting that in Go versions 1.7 and above, zero-byte reads return immediately without an error. Therefore, ensuring that at least one byte is read is crucial.

In conclusion, a robust approach involving SetReadDeadline(), Read() and handlingtimeouts allows you to reliably detect TCP connection closures in Go's net package.

The above is the detailed content of How Can I Reliably Detect TCP Connection Closure in Go?. 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