dsafew1231 2018-11-06 20:37
浏览 273
已采纳

Gorilla Websocket如何将二进制数据解组为JSON?

I'm following the chat example provided by gorilla.

I still can get to unmarshal the json data sent. Should I do this in the readPump():

func (c *ChatClient) readPump() {
    defer func() {
        c.hub.unregisterChan <- c
        c.conn.Close()
    }()
    c.conn.SetReadLimit(maxMessageSize)
    c.conn.SetReadDeadline(time.Now().Add(pongWait))
    c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
    for {
        _, message, err := c.conn.ReadMessage()
        // =================MY CODE START=============
        var comment Comment
        err = c.conn.ReadJSON(comment)
        if err != nil {
            LogErr("readjson()", err)
            break
        }
        err = json.Unmarshal(message, comment)
        if err != nil {
            LogErr("readjson()", err)
            break
        }
        // =================MY CODE END=============

        if err != nil {
            if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
                LogErr("IsUnexpectedCloseError()", err)
            }
            break
        }
        message = bytes.TrimSpace(bytes.Replace(message, newline, space, -1))
        c.hub.broadcastChan <- message
    }
}

or in the writePump()

func (c *ChatClient) writePump() {
    ticker := time.NewTicker(pingPeriod)
    defer func() {
        ticker.Stop()
        c.conn.Close()
    }()
    for {
        select {
        case message, ok := <-c.send:
            c.conn.SetWriteDeadline(time.Now().Add(writeWait))

            // CLOSE
            if !ok {
                c.conn.WriteMessage(websocket.CloseMessage, []byte{})
                return
            }

            w, err := c.conn.NextWriter(websocket.BinaryMessage)
            if err != nil {
                LogErr("c.conn.NextWriter", err)
                return
            }
            w.Write(message)

            // Add queued chat messages to the current websocket message.
            n := len(c.send)
            for i := 0; i < n; i++ {
                w.Write(newline)
                w.Write(<-c.send)
            }

            if err := w.Close(); err != nil {
                LogErr("w.Close()", err)
                return
            }
        case <-ticker.C:
            c.conn.SetWriteDeadline(time.Now().Add(writeWait))
            if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
                LogErr("c.conn.WriteMessage()", err)
                return
            }
        }
    }
}

The LogErr() methods don't print any message. Totally lost here.

  • 写回答

1条回答 默认 最新

  • donglusou3335 2018-11-06 21:03
    关注

    The application reads two messages on each iteration through the loop and attempts to unmarshal both to comment. Read one message only.

    The application calls ReadJSON and Unmarshal incorrectly and the error returned from these functions explains why: the application is attempting to unmarshal to a non-pointer.

    The application also sends the raw bytes of the message to a channel. That looks like it might be a leftover from whatever you are copying, so I'll ignore that in the remainder of the answer.

    Here's the fixed loop:

    for {
        var comment Comment
        err = c.conn.ReadJSON(&comment)
        if err != nil {
            if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
                LogErr("IsUnexpectedCloseError()", err)
            }
            break
        }
        // Do something with comment
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容