golang Socket长连接 模拟心跳

func Dotings(tcpConn *net.TCPConn) {
    data := make([]byte, 128)
    for {
        //读取数据
        res, _ := tcpConn.Read(data)
        str := string(data[:res])
        fmt.Println(str)
        
        messnager := make(chan byte)
        //检测每次Client是否有数据传来
        go GravelChannel(data[:res], messnager)
        //心跳计时
        go HeartBeating(tcpConn, messnager)
       }
}
func HeartBeating(tcpConn *net.TCPConn, readerChannel chan byte) {
    select {
    case <-time.After(time.Second * 5):
        tcpConn.Close()
    case <-readerChannel:
        break
    }
}
func GravelChannel(res []byte, mess chan byte) {
    for _, v := range res {
        mess <- v
    }
    close(mess)
}

按道理是如果经过5秒,客户端没有发来消息就会关闭连接,但当Client没有发消息时,感觉会阻塞到 res, err := tcpConn.Read(data) 这块。不能执行 go GravelChannel(data[:res], messnager) 和 go HeartBeating(tcpConn, messnager)
(求大神指点)

阅读 10.2k
1 个回答

你的思路有问题,tcpConn.Read(data)这块肯定会阻塞,等待着客户端的消息,如果要限时的话,使用tcpConn.SetDeadline(t time.Time)这个函数设定时间,设置5秒后的话可以是time.Now().Add(5 * time.Second),这样tcpConn.Read最后阻塞5秒然后就返回错误,并且err.Timeout()是true。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题