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.

图片转代码服务由CSDN问答提供 功能建议

因此,我对该示例进行了一些更改,使其可以与gin-gonic https://github.com/utiq/go-in-5-minutes/tree / master / episode4

许多客户端之间的Websocket握手是成功的。 问题在于,当客户端发送一条消息时,该消息不会传播到其余的客户端。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

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)
    })
    
    点赞 评论

相关推荐 更多相似问题