Shane Hou
Shane Hou

Reputation: 5018

Go TCP timeout not working?

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?

Upvotes: 2

Views: 4133

Answers (1)

zzzz
zzzz

Reputation: 91193

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.

Upvotes: 6

Related Questions