Bene
Bene

Reputation: 1281

GO Websocket send all clients a message

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

When Client1 sends a request to the Server, the Server responses to him instantly. But, the other clients can not see the response message.

So I want to make it go further: When a client sends a request to the server, the server will response to all clients so that all clients can see the message.

How can I do that? Any examples or nice tutorials for beginners?

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
      }
    }
}

Upvotes: 5

Views: 14584

Answers (1)

RoninDev
RoninDev

Reputation: 5686

You have to use connection pool to broadcast messages to all connections. You can use that as tutorial/sample http://gary.burd.info/go-websocket-chat

Simplifying:
Connection pool is a collection of registered connections. See 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's a connection pool
    connections map[*connection]bool

    ...
}

To broadcast message for all clients, we iterate over connection pool like this:

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

h.broadcast in that example is a channel with messages we need to broadcast.
We use default section of the select statement to delete connections with full or blocked send channels. See What is the benefit of sending to a channel by using select in Go?

Upvotes: 10

Related Questions