golang Socket长连接 模拟心跳
本文介绍了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)
(求大神指点)
解决方案
你的思路有问题,tcpConn.Read(data)这块肯定会阻塞,等待着客户端的消息,如果要限时的话,使用tcpConn.SetDeadline(t time.Time)
这个函数设定时间,设置5秒后的话可以是time.Now().Add(5 * time.Second)
,这样tcpConn.Read最后阻塞5秒然后就返回错误,并且err.Timeout()是true。
这篇关于golang Socket长连接 模拟心跳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文