gin-gonic和gorilla/websocket不会传播消息

huangapple go评论83阅读模式
英文:

gin-gonic and gorilla/websocket does not propagate message

问题

所以我对这个示例进行了一些更改,以使其与gin-gonic一起工作。

https://github.com/utiq/go-in-5-minutes/tree/master/episode4

许多客户端之间的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

得分: 1

我看了一下你在episode4提交更改

我的观察如下:

  • 你在流处理程序的每个传入请求上创建了一个hub实例。hub实例用于跟踪连接等,所以你在每个请求上都失去了它。
  • 你已经移除了索引/主页处理程序(可能你想将其转换为gin处理程序或其他什么,我不知道)。

现在,让我们让episode4起作用。请进行以下更改(根据你的喜好进行改进)。我已经使用下面的更改测试了你的episode4,它正常工作。

使/ws处理程序在server.go上工作:

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

connection.go上移除流处理程序:

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

server.go上添加索引HTML处理程序:(我添加了它来测试我的端点4)

r.SetHTMLTemplate(template.Must(template.ParseFiles("index.html")))
r.GET("/", func(c *gin.Context) {
    c.HTML(200, "index.html", nil)
})
英文:

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)
})

huangapple
  • 本文由 发表于 2017年6月20日 08:13:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/44641773.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定