V
V
VladimirDronik2020-01-06 19:28:32
go
VladimirDronik, 2020-01-06 19:28:32

How to send message only to specific user in gorilla websocket?

There is an application made according to the example:
https://gowebexamples.com/websockets/
html sends data to a websocket and receives a response. But how, when connecting, you can set the name or id of the client in order to send him messages from the server later?
In PHP, it did something like this:
the HTML client sends a connection request:
ws = new WebSocket("ws://199.120.133.176:48/?user=tester");
The server at the same time puts tester into the users array and then we can operate with this array. For example, we can send data to a specific user or all at once or selectively, in short, whatever.
How to implement this on GO?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
V
VladimirDronik, 2020-01-07
@VladimirDronik

Understood. Briefly it should be like this:

func main() {
 //создаем карту с пользователями
 users := make(map[string]*websocket.Conn)

  http.HandleFunc("/echo", func(w http.ResponseWriter, r *http.Request) {

  conn, _ := upgrader.Upgrade(w, r, nil) 

       //получаем id подключенного пользователя, который приходит в get параметре
       userId := r.URL.Query()["user"][0]

       // В консоли показываем какой пользователь подключился   
       fmt.Printf("User %s is connected \n", string(userId))
      //заносим в карту текущее подключение с ключем = id пользователя
        users[userId] = conn

This is how you can send a message to the socket for a specific user And this is how it is for everyone at once
for _, user := range users {
   user.WriteJSON(string(msg))
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question