Semaphore/api/sockets/pool.go

63 lines
1.2 KiB
Go
Raw Permalink Normal View History

2016-04-02 14:40:07 +02:00
package sockets
// hub maintains the set of active connections and broadcasts messages to the
// connections.
type hub struct {
// Registered connections.
connections map[*connection]bool
// Inbound messages from the connections.
2016-04-17 12:41:36 +02:00
broadcast chan *sendRequest
2016-04-02 14:40:07 +02:00
// Register requests from the connections.
register chan *connection
// Unregister requests from connections.
unregister chan *connection
}
2016-04-17 12:41:36 +02:00
type sendRequest struct {
userID int
msg []byte
}
2016-04-02 14:40:07 +02:00
var h = hub{
2016-04-17 12:41:36 +02:00
broadcast: make(chan *sendRequest),
2016-04-02 14:40:07 +02:00
register: make(chan *connection),
unregister: make(chan *connection),
connections: make(map[*connection]bool),
}
//nolint: gocyclo
2016-04-02 14:40:07 +02:00
func (h *hub) run() {
for {
select {
case c := <-h.register:
h.connections[c] = true
case c := <-h.unregister:
if _, ok := h.connections[c]; ok {
delete(h.connections, c)
close(c.send)
}
case m := <-h.broadcast:
for c := range h.connections {
2016-04-17 12:41:36 +02:00
if m.userID > 0 && m.userID != c.userID {
continue
}
2016-04-02 14:40:07 +02:00
select {
2016-04-17 12:41:36 +02:00
case c.send <- m.msg:
2016-04-02 14:40:07 +02:00
default:
close(c.send)
delete(h.connections, c)
}
}
}
}
}
// StartWS starts the web sockets in a goroutine
2016-04-02 14:40:07 +02:00
func StartWS() {
h.run()
}