-1

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

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

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

我正在使用github.com/garyburd/redigo/redisRedis 和 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还是需要类型转换?

4

1 回答 1

1

如文档中所述,参数 togob.NewEncoderio.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())
于 2017-08-29T15:52:58.647 回答