英文:
Encode websockets in Go with gob
问题
我正在使用Go语言编写一个使用Websockets的聊天应用程序。
应用程序中会有多个聊天室,我的想法是将连接到聊天室的所有Websockets存储在Redis列表中。
为了在Redis中存储和检索Websockets,我需要对它们进行编码/解码,根据这个问题的建议,我认为可以使用gob来实现。
我在Redis中使用github.com/garyburd/redigo/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
进行编码的整体思路错误了,还是需要进行类型转换?
英文:
I am writing a chat application using websockets in Go.
There will be multiple chat rooms and the idea is to store all the websockets connected to a chat room in a Redis list.
In order to store and retrieve the websockets in Redis I have to encode/decode them and (following this question) I thought that I can use gob for that.
I am using github.com/garyburd/redigo/redis
for Redis and github.com/gorilla/websocket
as my websocket library.
My function looks like:
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())
}
}
However, I am getting this 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)
What does this error mean? Is the whole idea of encoding the *websocket.Conn
wrong or type conversion is required?
答案1
得分: 1
根据文档的详细说明,gob.NewEncoder
的参数是你希望将编码结果写入的io.Writer
。它返回一个编码器,你需要将要编码的对象传递给它。它将对对象进行编码并将结果写入写入器。
假设conn
是你的Redis连接,你可以使用以下代码:
buff := new(bytes.Buffer)
err := gob.NewEncoder(buff).Encode(ws)
if err != nil {
// 处理错误
}
_, err := conn.Do("RPUSH", room, buff.Bytes())
这段代码将ws
对象编码并将结果写入buff
。然后,它使用Redis的RPUSH
命令将buff
的字节表示作为值推送到名为room
的列表中。
英文:
As detailed in the documentation, argument to gob.NewEncoder
is the io.Writer
you want the encoded result written to. This returns an encoder, to which you pass the object you want encoded. It will encode the object and write the result to the writer.
Assuming that conn
is your redis connection, you want something like:
buff := new(bytes.Buffer)
err := gob.NewEncoder(buff).Encode(ws)
if err != nil {
// handle error
}
_,err := conn.Do("RPUSH", room, buff.Bytes())
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论