42 lines
714 B
Go
42 lines
714 B
Go
package main
|
|
|
|
type hub struct {
|
|
connections map[*connection]bool
|
|
broadcast chan []byte
|
|
register chan *connection
|
|
unregister chan *connection
|
|
}
|
|
|
|
var h = hub{
|
|
broadcast: make(chan []byte),
|
|
register: make(chan *connection),
|
|
unregister: make(chan *connection),
|
|
connections: make(map[*connection]bool),
|
|
}
|
|
|
|
func (h *hub) run() {
|
|
for {
|
|
select {
|
|
case c := <-h.register:
|
|
h.connections[c] = true
|
|
|
|
case c := <-h.unregister:
|
|
_, ok := h.connections[c]
|
|
if ok {
|
|
delete(h.connections, c)
|
|
close(c.send)
|
|
}
|
|
|
|
case m := <-h.broadcast:
|
|
for c := range h.connections {
|
|
select {
|
|
case c.send <- m:
|
|
default:
|
|
close(c.send)
|
|
delete(h.connections, c)
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|