Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GO Websocket send all clients a message

Tags:

websocket

go

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
      }
    }
}
like image 371
Bene Avatar asked Feb 10 '23 12:02

Bene


1 Answers

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?

like image 167
RoninDev Avatar answered Feb 12 '23 02:02

RoninDev