我在 Golang 服务器和客户端上有两个项目。
问题是当我从服务器发送控制消息时,我无法通过客户端的类型获取它。
一些服务器代码示例:
发送 PingMessage:
ws.SetWriteDeadline(time.Now().Add(10 * time.Second))
ws.WriteMessage(websocket.PingMessage, new_msg)
发送关闭消息:
ws.WriteControl(websocket.CloseMessage,
websocket.FormatCloseMessage(websocket.CloseNormalClosure, "socket close"),
time.Now().Add(3 * time.Second))
客户端:
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
}
}
例如,我只能通过以下方式获得 CloseNormalClosure 消息:
if websocket.IsCloseError(err, websocket.CloseNormalClosure){
log.Warn("CloseNormalClosure message")
}
但是 PingMessage,我无法通过类型获取:
case websocket.PingMessage:
log.Warn("get ping!!!")
请你帮帮我,我做错了什么?
最佳答案
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.
将上面的代码写成:
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
}
}
大多数应用程序在出现任何错误时都会中断接收循环。更典型的做法是将上面的代码写成:
for {
t, socketMsg, err := ws.ReadMessage()
if err != nil {
break
}
SocketChannel <- socketMsg
}
关于go - Websocket控制消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48181255/