go - Websocket控制消息

标签 go gorilla

我在 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
}

关于go - Websocket控制消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48181255/

相关文章:

http - 有什么方法可以自定义 HTTP 响应状态?

regex - 在golang中捕获ping命令的结果

go - Golang 中使用 gorilla/mux 的静态文件服务器

html - 在 gorilla mux 中渲染 css js img 文件

Golang gorilla mux 未找到处理程序无法正常工作

go - 调用函数后重定向到另一个端点

go - 在golang中的表达式中检查括号是否平衡[保持]

go - 反向代理不起作用

dictionary - 将数据库中的数据转换为一张 map

go - 如何从处理程序内部按名称调用路由?