您现在的位置是:首页 >技术教程 >go net.conn SetReadDeadline的困惑网站首页技术教程

go net.conn SetReadDeadline的困惑

xiaowhy 2023-06-15 00:00:03
简介go net.conn SetReadDeadline的困惑

最近在用go写个工具,在几百个协程并行拿多个服务器数据时,用SetReadDeadline设置超时60s时,经常read返回失败,错误信息是timeout,而不设置SetReadDeadline时,反而正常,而且正常数据返回也不可能会超时60s,这是为什么呢?

recv部分的代码

/**
 * 接收数据包
 */
func RecvData(conn net.Conn, len int) ([]byte, bool) {

   var nTotalRecv int
   buff := make([]byte, len)
   nTotalRecv = 0
   for {
      if nTotalRecv >= len {
         break
      }
      //阻塞
      //conn.SetReadDeadline(time.Now().Add(60 * time.Second))

      nRecv, err := conn.Read(buff[nTotalRecv:])
      if err != nil {
         //if nerr, ok := err.(net.Error); ok && nerr.Timeout() {
         // log.Error("connect read conn timeout,continue to read.", err, " nRecv:", nRecv, ",totalrecv:", nTotalRecv, ",need read len:", len)
         // continue
         //} else {
         log.Error("connect read conn failed.", err, " nRecv:", nRecv, ",totalrecv:", nTotalRecv, ",need read len:", len)
         return buff, false
         //}
      }
      nTotalRecv += nRecv
   }
   return buff, true
}

                
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。