【问题标题】:Encode websockets in Go with gob使用 gob 在 Go 中编码 websocket
【发布时间】:2017-08-29 15:49:12
【问题描述】:

我正在用 Go 语言编写一个使用 websockets 的聊天应用程序。

会有多个聊天室,想法是将所有连接到聊天室的 websocket 存储在 Redis 列表中。

为了在 Redis 中存储和检索 websocket,我必须对它们进行编码/解码,并且(在this 问题之后)我认为我可以使用 gob。

我将 github.com/garyburd/redigo/redis 用于 Redis,github.com/gorilla/websocket 作为我的 websocket 库。

我的功能如下:

func addWebsocket(room string, ws *websocket.Conn) {
    conn := pool.Get()
    defer conn.Close()

    enc := gob.NewEncoder(ws)

    _, err := conn.Do("RPUSH", room, enc)
    if err != nil {
        panic(err.Error())
    }
}

但是,我收到此错误:

cannot use ws (type *websocket.Conn) as type io.Writer in argument to gob.NewEncoder: *websocket.Conn does not implement io.Writer (missing Write method) have websocket.write(int, time.Time, ...[]byte) error want Write([]byte) (int, error)

这个错误是什么意思?编码*websocket.Conn 的整个想法是错误的还是需要类型转换?

【问题讨论】:

    标签: go websocket gorilla redigo


    【解决方案1】:

    As detailed in the documentationgob.NewEncoder 的参数是您希望将编码结果写入的io.Writer。这将返回一个编码器,您将要编码的对象传递给该编码器。它将对对象进行编码并将结果写入编写器。

    假设 conn 是你的 redis 连接,你想要这样的东西:

    buff := new(bytes.Buffer)
    err := gob.NewEncoder(buff).Encode(ws)
    if err != nil {
        // handle error
    }
    _,err := conn.Do("RPUSH", room, buff.Bytes())
    

    【讨论】:

      猜你喜欢
      • 2012-12-16
      • 1970-01-01
      • 1970-01-01
      • 2021-06-14
      • 2012-06-27
      • 2021-08-04
      • 2015-04-18
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多