I have two projects on Golang server and client.
Problem is when I send controll message from server, i can't get it by type on client side.
Few server code example:
send PingMessage:
ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
ws.WriteMessage(websocket.PingMessage, new_msg)
send CloseMessage:
ws.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "socket close"),
time.Now().Add(3 * time.Second))
client side:
for{
t, socketMsg, err := ws.ReadMessage()
if websocket.IsUnexpectedCloseError(err) {
webSock.keepLive()
}
switch t {
case websocket.CloseNormalClosure:
webSock.keepLive()
case websocket.PingMessage:
log.Warn("get ping!!!")
case websocket.TextMessage:
SocketChannel <- socketMsg
}
}
for example CloseNormalClosure message i can get only with:
if websocket.IsCloseError(err, websocket.CloseNormalClosure){
log.Warn("CloseNormalClosure message")
}
But PingMessage, I can't get by type:
case websocket.PingMessage:
log.Warn("get ping!!!")
Could you help me, please, what Im doing wrong ?
The documentation says:
Connections handle received close messages by calling the handler function set with the SetCloseHandler method and by returning a *CloseError from the NextReader, ReadMessage or the message Read method. The default close handler sends a close message to the peer.
Connections handle received ping messages by calling the handler function set with the SetPingHandler method. The default ping handler sends a pong message to the peer.
Connections handle received pong messages by calling the handler function set with the SetPongHandler method. The default pong handler does nothing. If an application sends ping messages, then the application should set a pong handler to receive the corresponding pong.
Write the code above as:
ws.SetPingHandler(func(s string) error {
log.Warn("get ping!!!")
return nil
})
for {
t, socketMsg, err := ws.ReadMessage()
switch {
case websocket.IsCloseError(websocket.CloseNormalClosure):
webSock.keepLive()
case websocket.IsUnexpectedCloseError(err):
webSock.keepLive()
case t == websocket.TextMessage:
SocketChannel <- socketMsg
}
}
Most applications break out of the receive loop on any error. A more typical approach is to write the code above as:
for {
t, socketMsg, err := ws.ReadMessage()
if err != nil {
break
}
SocketChannel <- socketMsg
}
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