dtip91401 2017-06-20 00:13
浏览 92
已采纳

gin-gonic和大猩猩/ websocket不传播消息

So I made a few changes to this example to make it work with gin-gonic https://github.com/utiq/go-in-5-minutes/tree/master/episode4

The websocket handshake between many clients is succesful. The problem is that when a client sends a message, the message is not propagated to the rest of the clients.

  • 写回答

1条回答 默认 最新

  • dream2891 2017-06-20 20:03
    关注

    I had a look on your commit changes of episode4.

    My observations as follows:

    • You're creating hub instance on every incoming request at stream handler. hub instance used to keeps track connections, etc. so you're losing it on every request.
    • You have removed index/home handler (may be you wanted to convert to gin handler or something, I don't know).

    Now, let's bring episode4 into action. Please do following changes (as always improve it as you like). I have tested your episode4 with below changes, it's working fine.

    Make /ws handler work on server.go:

    h := newHub()
    wsh := wsHandler{h: h}
    r.GET("/ws", func(c *gin.Context) {
        wsh.ServeHTTP(c.Writer, c.Request)
    })
    

    Remove the stream handler on connection.go:

    func stream(c *gin.Context) {
        h := newHub()
        wsHandler{h: h}.ServeHTTP(c.Writer, c.Request)
    }
    

    Adding index HTML handler on server.go: (added it to test episode4 at my end)

    r.SetHTMLTemplate(template.Must(template.ParseFiles("index.html")))
    r.GET("/", func(c *gin.Context) {
        c.HTML(200, "index.html", nil)
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果