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

1

7

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?

Ress answered 8/6, 2016 at 7:57 Comment(0)
F
24

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.

Fructidor answered 8/6, 2016 at 14:32 Comment(4)
In the chat example, the frontend side seems to have nothing about ping-pong. Is it handled only on the backend side?Lanham
@anil The front end automatically responds to PING with a PONG. No code is required.Quagga
Would re-setting read dead line after every read alone work?Burnish
@Burnish Setting the read deadline before each read works if the application has a known upper bound for when the next message should be received at that upper bound is acceptable for detecting disconnects.Quagga

© 2022 - 2024 — McMap. All rights reserved.