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

huangapple go评论68阅读模式
英文:

How to check if a Conn is active without sending/receiving data?

问题

在Go/Golang中,一旦使用以下代码创建了一个连接对象(Conn):

conn, err := net.Dial("tcp", "33.33.33.33:444")
if err != nil {
  // 连接成功
}

我想保留conn的值,以便以后验证连接是否处于活动状态。我不想时不时重新连接以检查连接,因为这会在操作系统上引起各种TIME_WAIT,所以我的要求是:

  • 创建一个连接
  • 保留连接对象
  • 捕获连接由于任何原因而断开
  • 不发送或接收任何数据

有什么想法可以实现这一点吗?有没有办法在不发送或接收数据或重新连接的情况下捕获连接已断开?

英文:

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 ?

答案1

得分: 4

我不认为在不执行操作的情况下可以实现。如果很少使用,当你尝试读取时,如果客户端(或某个代理)关闭了连接,可能会出现错误。如果发生这种情况,重新连接并重试。

许多协议会内置心跳机制来促进这种情况。然后你可以不断地读取(如果需要,可以使用SetDeadline),并在心跳帧内知道是否出现了问题。

例如,我使用一个支持连接池的Redis客户端。当我从池中获取一个空闲连接时,我立即执行一个PING操作。如果成功,我就知道连接已经准备好使用。如果不成功,我会获取另一个空闲连接,或者重新连接。

英文:

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.

huangapple
  • 本文由 发表于 2015年10月30日 14:42:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/33430169.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定