fix: 修复普通heartbeat以及ws-heartbeat的return问题

main v1.2.5
NoahLan 1 year ago
parent cfa0409cc5
commit 10f91288bc

@ -28,8 +28,32 @@ func WithHeartbeat(interval time.Duration, hbdFn func(conn *conn.Connection) []b
panic("dataFn must not be nil") panic("dataFn must not be nil")
} }
var startFn event.OnConnectedFn = func(nc *conn.Connection) {
ticker := time.NewTicker(m.interval)
defer func() {
ticker.Stop()
}()
for {
select {
case <-ticker.C:
deadline := time.Now().Add(-2 * m.interval).Unix()
if atomic.LoadInt64(&m.lastAt) < deadline {
nlog.Errorf("Heartbeat timeout, LastTime=%d, Deadline=%d", atomic.LoadInt64(&m.lastAt), deadline)
break
}
err := nc.SendBytes(m.hbdFn(nc))
if err != nil {
nlog.Errorf("Heartbeat err: %v", err)
return
}
}
}
}
return func(ngin *nnet.Engine) { return func(ngin *nnet.Engine) {
ngin.EventManager().RegisterEvent(event.EvtOnConnected, m.start) ngin.EventManager().RegisterEvent(event.EvtOnConnected, startFn)
ngin.Use(func(next rt.HandlerFunc) rt.HandlerFunc { ngin.Use(func(next rt.HandlerFunc) rt.HandlerFunc {
return func(conn *conn.Connection, pkg packet.IPacket) { return func(conn *conn.Connection, pkg packet.IPacket) {
@ -41,30 +65,6 @@ func WithHeartbeat(interval time.Duration, hbdFn func(conn *conn.Connection) []b
} }
} }
func (m *HeartbeatMiddleware) start(conn *conn.Connection) {
ticker := time.NewTicker(m.interval)
defer func() {
ticker.Stop()
}()
for {
select {
case <-ticker.C:
deadline := time.Now().Add(-2 * m.interval).Unix()
if atomic.LoadInt64(&m.lastAt) < deadline {
nlog.Errorf("Heartbeat timeout, LastTime=%d, Deadline=%d", atomic.LoadInt64(&m.lastAt), deadline)
return
}
err := conn.SendBytes(m.hbdFn(conn))
if err != nil {
nlog.Errorf("Heartbeat err: %v", err)
return
}
}
}
}
func (m *HeartbeatMiddleware) handle(_ *conn.Connection, _ packet.IPacket) { func (m *HeartbeatMiddleware) handle(_ *conn.Connection, _ packet.IPacket) {
atomic.StoreInt64(&m.lastAt, time.Now().Unix()) atomic.StoreInt64(&m.lastAt, time.Now().Unix())
} }

@ -48,7 +48,7 @@ func WithHeartbeatWS(interval time.Duration, hbdFn WsHeartbeatFn) nnet.RunOption
deadline := time.Now().Add(-2 * m.interval).Unix() deadline := time.Now().Add(-2 * m.interval).Unix()
if atomic.LoadInt64(&m.lastAt) < deadline { if atomic.LoadInt64(&m.lastAt) < deadline {
nlog.Errorf("Heartbeat timeout, LastTime=%d, Deadline=%d", atomic.LoadInt64(&m.lastAt), deadline) nlog.Errorf("Heartbeat timeout, LastTime=%d, Deadline=%d", atomic.LoadInt64(&m.lastAt), deadline)
return break
} }
err := m.hbdFn(nc.WsConn()) err := m.hbdFn(nc.WsConn())

Loading…
Cancel
Save