I'm writing a chat program with Golang and Gorilla's Websocket toolkit.
I'm wondering if there is a way to run a function whenever a user disconnects or a ping/pong message fails. I need this to remove them from variables and such. Is there any easy way to do this?
The Websocket protocol implements so called PING/PONG messages to keep Websockets alive, even behind proxies, firewalls and load-balancers. The server sends a PING message to the client through the Websocket, which then replies with PONG. If the client does not reply, the server closes the connection.
Pings and Pongs: The Heartbeat of WebSockets At any point after the handshake, either the client or the server can choose to send a ping to the other party. When the ping is received, the recipient must send back a pong as soon as possible. You can use this to make sure that the client is still connected, for example.
GitHub - gorilla/websocket: A fast, well-tested and widely used WebSocket implementation for Go. Product. Actions. Copilot. Packages.
The application should close the connection and cleanup variables and such when the read methods (NextReader, ReadMessage) return an error.
Use ping/pong to detect disconnects. The chat example shows how to do this.
If a pong goes missing, the read methods will return with the read past deadline error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With