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 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化