dongqu4443 2019-06-11 02:39
浏览 380
已采纳

Golang Websocket自定义JSON消息

I'm trying to send/receive custom JSON messages. There are 3 cases in which the JSON struct changes, therefore I have 3 different structs. I have to access the room string which is sent as RawMessage. My question is what type should the channel Broadcast be?

type Message struct {
    Type int64 `json:"type"`
    Msg  json.RawMessage
}

Broadcast chan interface{} // ??? RawMessage or maybe interface

          case m := <-r.Broadcast:
            // What type should chan Broadcast be?
            // If m is of type json.RawMessage should I deal with unmarshalling here?
            connections := r.Clients[m.Room] // 
            for c := range connections {
                select {
                case c.send <- m:
                default:
                    close(c.send)
                    delete(connections, c)
                    if len(connections) == 0 {
                        delete(r.Clients, m.Room)
                    }
                }
            }
for {
        msg := &Message{}
        err := c.conn.ReadJSON(&msg)
        // _, msg, err := c.conn.ReadMessage()
        if err != nil {
            if websocket.IsUnexpectedCloseError(err, websocket.CloseGoingAway, websocket.CloseAbnormalClosure) {
                log.Printf("error: %v", err)
            }
            break
        }

        if msg.Type == 0 {
            newVideo := &NewVideo{}
            if err = json.Unmarshal(msg.Msg, &newVideo); err != nil {
                fmt.Println(err)
            }
            Roomb.Broadcast <- msg.Msg // ??? should i send the RawMessage
            online[msg.Room] = msg
        } else if msg.Type == 1 {
            if _, ok := online[msg.Room]; ok {
                online[msg.Room].Start = float64(time.Now().Unix() - online[msg.Room].Timestamp)
                c.send <- online[msg.Room]
            }
        } else if msg.Type == 2 {
            Roomb.Broadcast <- msg.Msg // ??? should i send the RawMessage
        }
        fmt.Println(msg)
    }
  • 写回答

1条回答 默认 最新

  • doushan2811 2019-06-11 05:49
    关注
    1. Remove the "&" before msg. msg is already a pointer. This may make problems.

    2. Your question is not very clear. If msg.Type defines what the msg.Msg is, then I recommend you make channels typed with the actual message type, parse the msg.Msg, then send it through the channel.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 模电中二极管,三极管和电容的应用
  • ¥15 关于模型导入UNITY的.FBX: Check external application preferences.警告。
  • ¥15 气象网格数据与卫星轨道数据如何匹配
  • ¥100 java ee ssm项目 悬赏,感兴趣直接联系我
  • ¥15 微软账户问题不小心注销了好像
  • ¥15 x264库中预测模式字IPM、运动向量差MVD、量化后的DCT系数的位置
  • ¥15 curl 命令调用正常,程序调用报 java.net.ConnectException: connection refused
  • ¥20 关于web前端如何播放二次加密m3u8视频的问题
  • ¥15 使用百度地图api 位置函数报错?
  • ¥15 metamask如何添加TRON自定义网络