如何在不发送/接收数据的情况下检查Conn是否处于活动状态?

In Go/Golang, once a connection object (Conn) is created with the following code:

conn, err := net.Dial("tcp","33.33.33.33:444")
if err != nil {
  // good connection
}

I would like to preserve the conn value for later on verifying if the connection is active. I dont want to re-connect from time to time to check the connection as it causes various TIME_WAITs on the OS, so overall my requirements are:

  • create a connection
  • preserve the connection object
  • capture if the connection drops for any reason
  • do not send or receive any data

Any thoughts on how to achieve this ? Is there a way to capture that the connection is discontinued without sending or receiving data or reconnecting ?

I don't think it is possible to do without performing an operation. If it is infrequently used, when you try to read you may get an error if the client (or some proxy) closed the connection. If that happens then reconnect and retry.

Many protocols will bake in a heartbeat mechanism to facilitate this kind of thing. Then you can read constantly (with SetDeadline if you want) and know within a heartbeat frame that something went wrong.

For example, I use a redis client that supports connection pooling. When I retrieve an idele connection from the pool, I immediately perform a PING operation. If that succeeds, I know the connection is ready to use. If not, I get another idle one, or connect anew.