douxie1692 2017-08-29 15:49
浏览 90
已采纳

使用gob在Go中编码websocket

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条回答 默认 最新

  • dongxiangchan0743 2017-08-29 15:52
    关注

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

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题