英文:
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)
})
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论