dongxin991209 2015-04-26 11:27
浏览 46
已采纳

使goroutine中的TCP连接保持活动状态,并检查连接是否丢失是否超时

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
", 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)
}
  • 写回答

1条回答 默认 最新

  • douji3623 2015-04-26 12:21
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序
  • ¥15 onvif+openssl,vs2022编译openssl64