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

我正在尝试使用Go学习网络套接字。 我一直在看大猩猩websocket的示例。</ p>

我已经查看了这两个示例,展示了如何使用大猩猩websocket:</ p>

https://github.com/gorilla/websocket/tree/master/examples </ p >

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

所有这些示例都展示了如何连接到Websocket服务器,发送和接收文本。 但是我不明白的是,如何只能发送给一个客户。 因为在真实的应用程序中您将拥有用户,所以我们不希望所有用户都收到相同的消息和相同的数据。 有没有办法让我获取一个连接的唯一ID,我可以将其保存在像redis这样的数据库中,并将其链接到同一数据库中的用户ID,然后使用该websocket ID发送回特定的客户端(如果这样) 用户ID收到消息或通知? 这是如何实现这样的目标吗? 如果是这样,那我该怎么办?</ p>
</ div>

展开原文

原文

I am trying to learn websockets with Go. I have been looking at examples with gorilla websocket.

I have checked out these 2 examples that show how to use gorilla websocket:

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

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

All of these examples show how to connect to a websocket server, send and receive texts. But what I don't understand is how you can send to only one client. Because in a real world application you will have users, and we don't want all users to receive the same message and same data. 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? Is this how one would go about and achieve something like this? If that is the case, how would I that?

dongliuzi3410
dongliuzi3410 我同意@BravadaZadada。有多种方法可以完成此操作,但是您的需求是基本的。只需分配任何新的websocket。在地图中连接一个唯一的密钥,当您准备对其进行写入时,调用mapname[“clientname”]。WriteMessage(1,[]byte(msg))
大约 5 年之前 回复
douhuang1852
douhuang1852 将Gorilla集线器字段从connectionsmap[*connection]bool更改为connectionsmap[string]*connection,其中字符串键是id。将id字符串字段添加到连接。创建连接并为地图类型进行较小更改时分配ID。完成。
大约 5 年之前 回复

1个回答

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?

Sure! You can generate Id by yourself while user registering. Just add userId field in connection structure

In chat example you have hub, which contains connections pool. That pool is using to broadcast messages to all users:

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

So there you go. You should make method to send private message, depend on userId

doushizhou4477
doushizhou4477 很高兴看到您通过id选择或忽略的示例...
大约 2 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问
相关内容推荐