GO Websocket send all clients a message -


everything works fine code (shortened better reading).

when client1 sends request server, server responses him instantly. but, other clients can not see response message.

so want make go further: when client sends request server, server response clients clients can see message.

how can that? examples or nice tutorials 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     }     {       messagetype, p, err := conn.readmessage()        if err != nil {         return       }        print_binary(p) // simple print of message        err = conn.writemessage(messagetype, p);       if err != nil {         return       }     } } 

you have use connection pool broadcast messages connections. can use tutorial/sample http://gary.burd.info/go-websocket-chat

simplifying:
connection pool collection of registered connections. see hub.connections:

type connection struct {     // websocket connection.     ws *websocket.conn      // buffered channel of outbound messages.     send chan []byte      // hub.     h *hub }  type hub struct {     // registered connections. that's connection pool     connections map[*connection]bool      ... } 

to broadcast message clients, iterate on connection pool this:

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

h.broadcast in example channel messages need broadcast.
use default section of select statement delete connections full or blocked send channels. see what benefit of sending channel using select in go?


Comments