Below is the code of my websocket server.
http.Handle("/gatewayconnector", websocket.Handler(socketHandler))
Method socketHandler has the code below:
func socketHandler(ws *websocket.Conn) {
LoadClient(ws)
var msg []byte
for {
if err := websocket.Message.Receive(ws, &msg); err != nil {
log.Error("Error in socketHandler: ", err)
break
}
validateMessage(msg)
}
}
The socket handler call back method get called when handshake happened from client and it also initiate the websocket object. So at very first step of this method i stored this websocket object into an array, so that i can retrieve it at the send method call (used to send message to client).
The issue is sometimes I'm getting nil memory reference in ws i.e. the websocket while trying to send some message to client.
Below is the send method code:
func Send(msg interface{}) error {
ws := webSocketClients[0]
if (ws == nil) {
log.Error("Websocket connection is nil, gateway should initiate the connection.")
}
return websocket.JSON.Send(ws, msg)
}
This issue arises when websocket connection remanis idle for a longer persiod of time and I call directly the send method.
Right now i have put one hack that client will ping my websocket server at regular interval to avoid this.
How to avoid this kind of problem?
Pinging websocket connection on interval is normal thing to do, please check how it's done in Gorilla Websocket Chat Example. I know you're using net/websocket
, but the idea should be similar. The problem is that you can't rely that your long-time TCP connection will remain active, especially in public networks. Some firewalls silently RST connections without traffic flow after some period of time.