如何只发送给一个客户端,而不是所有使用Go和大猩猩websocket的客户端 [英] How to send to only one client and not all clients using Go and gorilla websocket

查看:185
本文介绍了如何只发送给一个客户端,而不是所有使用Go和大猩猩websocket的客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Go学习websocket。我一直在看大猩猩websocket的例子。



我已经检查了这两个例子,展示了如何使用大猩猩websocket:

https://github.com/gorilla/websocket/tree/master/示例



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



所有这些示例都显示了如何连接到websocket服务器,发送和接收文本。但我不明白的是如何只能发送给一个客户端。因为在真实世界的应用程序中,您将拥有用户,并且我们不希望所有用户都收到相同的消息和相同的数据。有没有办法让我得到一个连接的唯一ID,我可以像redis一样将它保存在数据库中,并将它连接到同一个数据库中的用户ID,然后使用该websocket ID发送回特定的客户端用户ID收到消息或通知?这是如何去做和实现这样的事情?如果是这样的话,我该怎么做?

解决方案


有没有办法让我获取连接的唯一标识,我可以将
保存在数据库中,例如redis,并将其链接到同一
数据库中的用户标识,然后使用该websocket标识将其发送回特定的
客户端,如果该用户ID收到一条消息或通知?


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



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

  case m:= <-h.broadcast:
对于c:=范围h.connections {
select {
case c.send< - m:
default:
close(c.send)
delete h.connections,c)
}
}
}

所以你去了。你应该让方法发送私人消息,取决于userId


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?

解决方案

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

这篇关于如何只发送给一个客户端,而不是所有使用Go和大猩猩websocket的客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆