gpt4 book ai didi

go - 如何使用 Go 和 gorilla websocket 只发送给一个客户端而不是所有客户端

转载 作者:IT王子 更新时间:2023-10-29 01:48:09 26 4
gpt4 key购买 nike

我正在尝试使用 Go 学习 websockets。我一直在看 gorilla websocket 的例子。

我已经查看了这两个展示如何使用 gorilla websocket 的示例:

https://github.com/gorilla/websocket/tree/master/examples

https://www.youtube.com/watch?v=ysAZ_oqPOo0

所有这些示例都展示了如何连接到 websocket 服务器、发送和接收文本。但我不明白的是你如何只发送给一个客户。因为在现实世界的应用程序中,您会有用户,我们不希望所有用户都收到相同的消息和相同的数据。有没有办法让我获取连接的唯一 ID,我可以将其保存在像 Redis 这样的数据库中,并将其链接到同一数据库中的用户 ID,然后使用该 WebSocket ID 发送回特定客户端(如果有)用户 id 收到消息或通知?这是一个人会如何去实现这样的事情吗?如果是这样,我会怎么做?

最佳答案

Is there a way for me to get the unique id of a connection which I can save in a database like redis and link it to a user id in the same database, and then use that websocket id to send back to a specific client if that user id received a message or a notification?

当然!您可以在用户注册时自行生成Id。只需在 connection 结构中添加 userId 字段

在聊天示例中,您有集线器,其中包含连接池。该池用于向所有用户广播消息:

case m := <-h.broadcast:
for c := range h.connections {
select {
case c.send <- m:
default:
close(c.send)
delete(h.connections, c)
}
}
}

就这样吧。您应该根据 userId 制定发送私有(private)消息的方法

关于go - 如何使用 Go 和 gorilla websocket 只发送给一个客户端而不是所有客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31598147/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com