2 years ago
#61068
Liam Kelly
How to ensure non-blocking behavior from TCPConn SetDeadline to check from dead peers?
The following question compiles several ways to check for dead peers in TCP connections: How to know TCP connection is closed in net package?
After researching this more, the typical situation boils down to:
- The operating system gets a FIN and puts the socket into a CLOSE_WAIT state
- The application needs to issue a socket read in order to detect this state
The main problem is that if you are not monitoring the socket for data at the moment, but still need to detect if it is closed, then you need to poll the status with the read (or read/peek). Given that the default TCPConn Read in go is blocking, the accepted solutions use SetReadDeadline to try to get it to behave in a nonblocking way to make it behave like a poll.
The issue is that SetReadDealine, at least on my go version/architecture, only works when the value given is greater than Time.Now()
. So the question becomes, given the following code segment, what is the minimum value for DeadlineDuration
that will guarantee dead peer detection?
one := make([]byte,1)
c.SetReadDeadline(time.Now() + DeadlineDuration)
if _, err := c.Read(one); err == io.EOF {
c.Close()
}
linux
go
tcp
network-programming
0 Answers
Your Answer