douwei1950 2015-07-23 21:14 采纳率: 0%
浏览 926

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

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?

  • 写回答

1条回答 默认 最新

  • duanqian6295 2015-07-23 22:04
    关注

    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

    评论

报告相同问题?

悬赏问题

  • ¥15 fluent的在模拟压强时使用希望得到一些建议
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏
  • ¥15 模糊pid与pid仿真结果几乎一样
  • ¥15 java的GUI的运用
  • ¥15 Web.config连不上数据库
  • ¥15 我想付费需要AKM公司DSP开发资料及相关开发。
  • ¥15 怎么配置广告联盟瀑布流
  • ¥15 Rstudio 保存代码闪退