How to send to only one client and not all clients using Go and gorilla websocket

前端 未结 1 1975
醉话见心
醉话见心 2021-01-14 16:21

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 web

1条回答
  •  清酒与你
    2021-01-14 16:42

    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

    0 讨论(0)
提交回复
热议问题