英文:
Realtime push notification golang
问题
我想在我的Web应用程序中实现实时通知功能。我正在按照这个示例"https://github.com/gorilla/websocket/tree/master/examples/chat"进行操作。我需要服务器(hub)接收消息,并根据某种ID将这些消息推送给各个客户端。我该如何做到这一点?
英文:
I want to implement a real time notification feature in my web application. I am following this example "https://github.com/gorilla/websocket/tree/master/examples/chat". I need the server (hub) to get messages, it needs to push those messages to individual clients based on some form of ID. how can I do this?
答案1
得分: 1
从你提到的示例中:
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
这是向所有客户端广播消息的情况。正如你所看到的,它遍历所有注册的客户端,并将消息发送给每一个客户端。
为了保留这个功能,我们只需要添加另一个情况:向单个客户端发送消息。
case message := <-h.clientMessage:
for client := range h.clients {
if message.ClientID == client.ID {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
这应该给你一个思路。其余的部分由你来完成。
注意:我的示例代码可以通过使用map[clientID]Client
来直接访问客户端来进行优化。
英文:
From the sample you mentioned:
case message := <-h.broadcast:
for client := range h.clients {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
This is the case where a message is broadcasted to all clients. As you can see it loops over all registered clients and sends the message to every single one of them.
To preserve this functionality we will simply add another case: send to a single client.
case message := <-h.clientMessage:
for client := range h.clients {
if message.ClientID == client.ID {
select {
case client.send <- message:
default:
close(client.send)
delete(h.clients, client)
}
}
}
}
This should give you an idea. The rest I leave up to you.
Note: my sample code can be optimised by e.g. using a map[clientID]Client
to access the client directly.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论