Go TCP超时不起作用?

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

Go TCP timeout not working?

问题

我正在使用net.Listen()来监听来自客户端的TCP连接。

当客户端建立连接时,Handler(conn net.Conn)将处理它。

func Handler(conn net.Conn) {

  read_len, err := conn.Read(request)

  if err != nil {
    if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
      fmt.Println(neterr)
      PILOG("客户端超时!", PILOGWARNING)
      conn.Close()
      return
  }
}

我使用了一个测试客户端连接,然后突然关闭客户端而没有发送DISCONNECT消息。当达到超时时,我的服务器应该关闭连接,但是经过很长时间等待后,这种情况从未发生。

我还尝试了conn.SetReadDeadline(time.Now()),但似乎仍然不起作用。所以我想知道go中默认的TCP超时时间是多少,以及如何设置它?

我还使用了netstat -n命令,在关闭客户端后得到了以下结果:

tcp4 0 0 127.0.0.1.12345 127.0.0.1.57296 CLOSE_WAIT

CLOSE_WAIT是什么意思?

英文:

I'm using net.Listen() to listen TCP connections from clients.

When client established a connection, Handler(conn net.Conn) will handle it.

func Handler(conn net.Conn) {

  read_len, err := conn.Read(request)

  if err != nil {
    if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
      fmt.Println(neterr)
      PILOG("Client timeout!", PILOGWARNING)
      conn.Close()
      return
  }
}

I used a test client to connect then kill the client suddenly without sending a DISCONNECT message. My server should close the connection when reached timeout, but after a long waiting time it never happen.

I've also tried conn.SetReadDeadline(time.Now()) but seems it still not working. So I wonder what the default TCP timeout in go, and how can I set it?

I also used netstat -n and got the result below after killed the client:

tcp4 0 0 127.0.0.1.12345 127.0.0.1.57296 CLOSE_WAIT

What does CLOSE_WAIT mean?

答案1

得分: 6

SetReadDeadline 在我所知的情况下是有效的,但是 SetReadDeadline(time.Now()) 没有合理的用途,这就是问题所在,我相信。要从现在开始设置一个超时时间,例如 N 秒,可以使用以下代码:

SetReadDeadline(time.Now().Add(N*time.Second))

来自Wikipedia

> CLOSE-WAIT
>
> (服务器和客户端都)表示等待来自本地用户的连接终止请求。

英文:

SetReadDeadline works AFAIK, but SetReadDeadline(time.Now()) has no reasonable use and that's the problem, I believe. To make a timeout of, for example N seconds from now use:

SetReadDeadline(time.Now().Add(N*time.Second))

From Wikipedia

> CLOSE-WAIT
>
> (both server and client) represents waiting for a connection termination request from the local user.

huangapple
  • 本文由 发表于 2013年4月12日 20:08:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/15971038.html
匿名

发表评论

匿名网友

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

确定