I'm naively use _, err := ws.Read(msg) to keep a Web socket open in my code. I don't think it works reliably.
In other code I've noticed people doing a sleep loop. What's the correct way to keep a Web socket open & stable? I assume the underlying library does ping/pongs?
Update: I'm pretty confident that the client.go is to blame since it doesn't seem to redial after a disconnect is seen on the server. I made a video demonstrating the issue.
golang.org/x/net/websocket does not implement ping-pong from RFC 6455, but the gorilla websocket implementation does. Minimal example with Gorilla websocket
c := time.Tick(pingInterval)
go func(){
for _ := range c {
if err := conn.WriteControl(Ping...); err != nil {
handle error
}
}
}()
-----
conn.SetPongHandler(func(string) error { return conn.SetReadDeadline(time.Now().Add(pingInterval)) })
go func(){
for {
if _, _, err := conn.NextReader(); err != nil {
handle error
}
}
}()
I misread your original question.
No you're doing it the right away. You basically need to block the handler from returning to keep the websocket connection alive. If you don't care about the message, just discard it and do nothing with it.
A common way people do it is to have a dedicated Read
and Write
goroutine, something like:
func fishHandler(ws *websocket.Conn) {
id := ws.RemoteAddr().String() + "-" + ws.Request().RemoteAddr + "-" + ws.Request().UserAgent()
sockets[id] = ws
go writePump(ws)
readPump(ws)
}
func readPump(ws *websocket.Conn) {
defer ws.Close()
msg := make([]byte, 512)
_, err := ws.Read(msg)
if err != nil {
return
}
}
func writePump(ws *websocket.Conn) {
// Hand the write messages here
}
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