optimize ping/pong code
This commit is contained in:
parent
d975034680
commit
32e00480f8
2 changed files with 6 additions and 9 deletions
|
@ -22,17 +22,16 @@ func SendPermanentBroadCastMessage() {
|
|||
|
||||
// Iterate over all connected clients and broadcast the message
|
||||
for _, client := range Clients {
|
||||
if time.Now().Sub(client.LastPong) > (10 * time.Second) {
|
||||
// Remove unresponsive client
|
||||
client.Conn.Close()
|
||||
}
|
||||
err := client.SendMessage(websocket.TextMessage, jsonMessage)
|
||||
if err != nil {
|
||||
helper.Logger.Info("Error broadcasting to client:", "msg", err, "host", client.RealIP, "clients", len(Clients))
|
||||
}
|
||||
}
|
||||
for _, client := range Clients {
|
||||
if time.Now().Sub(client.LastPong) > (10 * time.Second) {
|
||||
// Remove unresponsive client
|
||||
client.Conn.Close()
|
||||
}
|
||||
}
|
||||
|
||||
<-tick.C
|
||||
}
|
||||
}
|
||||
|
|
|
@ -23,15 +23,13 @@ type WebsocketClient struct {
|
|||
}
|
||||
|
||||
// Sends a message to the websocket.
|
||||
// Automatically locks and unlocks the client mutex, to ensure that only one goroutine can write at a time.
|
||||
func (c *WebsocketClient) SendMessage(messageType int, data []byte) error {
|
||||
c.Conn.SetPongHandler(func(s string) error {
|
||||
c.LastPong = time.Now()
|
||||
return nil
|
||||
})
|
||||
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
|
||||
c.Conn.WriteMessage(websocket.PingMessage, nil)
|
||||
|
||||
c.Conn.SetWriteDeadline(time.Now().Add(TIMEOUT * time.Second))
|
||||
c.Conn.WriteMessage(websocket.PingMessage, nil)
|
||||
return c.Conn.WriteMessage(messageType, data)
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue