Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Go Gorilla Websockets ~ On ping/pong fail (user disconnct) call function?

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?

like image 598
Ari Seyhun Avatar asked Jun 08 '16 07:06

Ari Seyhun


People also ask

Do Ping Pong do WebSockets?

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.

How does Websocket ping pong work?

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.

What is Gorilla Websocket?

GitHub - gorilla/websocket: A fast, well-tested and widely used WebSocket implementation for Go. Product. Actions. Copilot. Packages.


1 Answers

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.

  • Send pings on a regular interval.
  • Set read deadline to a time less than next expected pong.
  • Reset the read deadline when a pong is received.

If a pong goes missing, the read methods will return with the read past deadline error.

like image 75
Bayta Darell Avatar answered Sep 28 '22 04:09

Bayta Darell