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 }
This approach involves:
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 }
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!