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
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥15 stable diffusion
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘