Websocket 控制消息

Websocket Control Message

我在 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!!!")

你能帮帮我吗,我做错了什么?

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.

将上面的代码写成:

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
}