user123577
user123577

Reputation: 121

Keeping a TCP connection alive in a goroutine and check if it timesout if the connection is lost

I have a TCP server up and running listetning to a port and a go routine for handeling the connections. I wonder if it's possible to have a go routine running for every connection keeping them alive with net.SetKeepAlive(true). Also with error handling so that if the connection times out it will execute cleanup functions like removing the connection from a list?

Handle routine:

func handleConnection(conn net.Conn, rec chan string) {
   var item QueItem
   buf := make([]byte, bufSize)
   l, err := conn.Read(buf)
   if err != nil || l < 0 {
    fmt.Println("Error reading from conn: ", conn)
    fmt.Println("Error reading: ", err)
   }

   err = json.Unmarshal(buf[:l], &item)
   if err != nil {
     fmt.Println("Error converting to JSON", jErr)
   }

  fmt.Printf("Received : %+v\n", item)
  fmt.Println("recived from:", conn.RemoteAddr())
  rec <- item.IP
}

TCPserver:

for {
    conn, err := ln.Accept()
    if err != nil {
        fmt.Println("No accept", err)
        log.Println("Unable to accept connection", err)
    }
    go handleConnection(conn, recived)
}

Upvotes: 1

Views: 2492

Answers (1)

Prabhu
Prabhu

Reputation: 3541

To keep a check on the established TCP connections, one can do keep-alive mechanism in two ways.

At application level: In idle conditions both client and server agree on a protocol to send pre-determined packets to each other. Lack of a message from peer with in certain time can signal a problem in the connection.

At TCP layer: Enable the TCP stack to check the connection status. The TCP layer at which this mechanism is enabled will send keep-alive messages at regular determined interval. It would expect that the peer TCP stack send keep-alive-ack. Absence of ACK after needed re-transmission signals connection problem and the application would be duly notified.

I think net.SetKeepAlive(true) is a go way of informing the TCP to do keep-alive. You need not do any thing special constructs in go routine.

TCP keep-alive works well. Application need not be burdened to check for connection status

Upvotes: 4

Related Questions