Created
September 11, 2022 05:22
-
-
Save percybolmer/9e60d334081397c032453971541bb74c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// writeMessages is a process that listens for new messages to output to the Client | |
func (c *Client) writeMessages() { | |
// Create a ticker that triggers a ping at given interval | |
ticker := time.NewTicker(pingInterval) | |
defer func() { | |
ticker.Stop() | |
// Graceful close if this triggers a closing | |
c.manager.removeClient(c) | |
}() | |
for { | |
select { | |
case message, ok := <-c.egress: | |
// Ok will be false Incase the egress channel is closed | |
if !ok { | |
// Manager has closed this connection channel, so communicate that to frontend | |
if err := c.connection.WriteMessage(websocket.CloseMessage, nil); err != nil { | |
// Log that the connection is closed and the reason | |
log.Println("connection closed: ", err) | |
} | |
// Return to close the goroutine | |
return | |
} | |
data, err := json.Marshal(message) | |
if err != nil { | |
log.Println(err) | |
return // closes the connection, should we really | |
} | |
// Write a Regular text message to the connection | |
if err := c.connection.WriteMessage(websocket.TextMessage, data); err != nil { | |
log.Println(err) | |
} | |
log.Println("sent message") | |
case <-ticker.C: | |
log.Println("ping") | |
// Send the Ping | |
if err := c.connection.WriteMessage(websocket.PingMessage, []byte{}); err != nil { | |
log.Println("writemsg: ", err) | |
return // return to break this goroutine triggeing cleanup | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment