2014-04-19 01:25:11 +04:00
|
|
|
// Copyright 2013 The Gorilla WebSocket Authors. All rights reserved.
|
2013-10-16 20:41:47 +04:00
|
|
|
// Use of this source code is governed by a BSD-style
|
|
|
|
// license that can be found in the LICENSE file.
|
|
|
|
|
|
|
|
package main
|
|
|
|
|
|
|
|
// 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.
|
|
|
|
broadcast chan []byte
|
|
|
|
|
|
|
|
// Register requests from the connections.
|
|
|
|
register chan *connection
|
|
|
|
|
|
|
|
// Unregister requests from connections.
|
|
|
|
unregister chan *connection
|
|
|
|
}
|
|
|
|
|
2016-05-18 17:56:16 +03:00
|
|
|
var mainHub = hub{
|
2013-10-16 20:41:47 +04:00
|
|
|
broadcast: make(chan []byte),
|
|
|
|
register: make(chan *connection),
|
|
|
|
unregister: make(chan *connection),
|
|
|
|
connections: make(map[*connection]bool),
|
|
|
|
}
|
|
|
|
|
2016-05-18 17:56:16 +03:00
|
|
|
func (hub *hub) run() {
|
2013-10-16 20:41:47 +04:00
|
|
|
for {
|
|
|
|
select {
|
2016-05-18 17:56:16 +03:00
|
|
|
case c := <-hub.register:
|
|
|
|
hub.connections[c] = true
|
|
|
|
case c := <-hub.unregister:
|
|
|
|
if _, ok := hub.connections[c]; ok {
|
|
|
|
delete(hub.connections, c)
|
2014-06-28 00:08:22 +04:00
|
|
|
close(c.send)
|
|
|
|
}
|
2016-05-18 17:56:16 +03:00
|
|
|
case m := <-hub.broadcast:
|
|
|
|
for c := range hub.connections {
|
2013-10-16 20:41:47 +04:00
|
|
|
select {
|
|
|
|
case c.send <- m:
|
|
|
|
default:
|
|
|
|
close(c.send)
|
2016-05-18 17:56:16 +03:00
|
|
|
delete(hub.connections, c)
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|