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

How Can I Detect TCP Connection Closure in Go's `net` Package?

Susan Sarandon
Release: 2024-12-16 21:52:15
Original
655 people have browsed it

How Can I Detect TCP Connection Closure in Go's `net` Package?

How to Determine TCP Connection Closure Using the Net Package

Problem:

When implementing a TCP server, it's essential to know when clients close their connections. How can you determine this using the net package?

Answer:

To detect a closed TCP connection, you can use the following method:

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

This approach involves:

  1. Creating a single-byte buffer (one).
  2. Setting a read deadline on the connection (c) to the current time to force an immediate read.
  3. Reading a byte from the connection.
  4. Checking the error; if it's io.EOF, the connection has closed.

Timeout Detection:

To detect a timeout, you can check if the error is a net.Error with a timeout.

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

Update (Go 1.7 ):

In Go 1.7 , zero-byte reads return immediately and never result in an error. To account for this, it's necessary to read at least one byte.

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