GO Websocket sends a message to all clients

Everything works fine with this code (shortened for better reading).

When it Client1sends a request to the server, the server instantly responds to it. But other clients cannot see the response message.

So, I want to do this further: when a client sends a request to the server, the server will respond to all clients so that all clients can see this message.

How can i do this? Any examples or good primers?

Thanks in advance!

Server:

import (
        "github.com/gorilla/websocket"
       )

func main() {
    http.Handle("/server", websocket.Handler(echoHandler)) 
}

func echoHandler(ws *websocket.Conn) {
    conn, err := upgrader.Upgrade(w, r, nil) 
    if err != nil { 
      return
    }
    for {
      messageType, p, err := conn.ReadMessage() 
      if err != nil {
        return
      }

      print_binary(p) // simple print of the message

      err = conn.WriteMessage(messageType, p);
      if err != nil {
        return
      }
    }
}
+4
source share
1 answer

You must use the connection pool to send messages to all connections. You can use this as a tutorial / sample http://gary.burd.info/go-websocket-chat

:
- . . hub.connections:

type connection struct {
    // The websocket connection.
    ws *websocket.Conn

    // Buffered channel of outbound messages.
    send chan []byte

    // The hub.
    h *hub
}

type hub struct {
    // Registered connections. That a connection pool
    connections map[*connection]bool

    ...
}

:

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

h.broadcast , .
default select . . select Go?

+5

Source: https://habr.com/ru/post/1598830/


All Articles