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.
|
2016-05-27 07:00:24 +03:00
|
|
|
type Hub struct {
|
2013-10-16 20:41:47 +04:00
|
|
|
// Registered connections.
|
2016-05-27 07:00:24 +03:00
|
|
|
connections map[*Conn]bool
|
2013-10-16 20:41:47 +04:00
|
|
|
|
|
|
|
// Inbound messages from the connections.
|
|
|
|
broadcast chan []byte
|
|
|
|
|
|
|
|
// Register requests from the connections.
|
2016-05-27 07:00:24 +03:00
|
|
|
register chan *Conn
|
2013-10-16 20:41:47 +04:00
|
|
|
|
|
|
|
// Unregister requests from connections.
|
2016-05-27 07:00:24 +03:00
|
|
|
unregister chan *Conn
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
|
2016-05-27 07:00:24 +03:00
|
|
|
var hub = Hub{
|
2013-10-16 20:41:47 +04:00
|
|
|
broadcast: make(chan []byte),
|
2016-05-27 07:00:24 +03:00
|
|
|
register: make(chan *Conn),
|
|
|
|
unregister: make(chan *Conn),
|
|
|
|
connections: make(map[*Conn]bool),
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
|
2016-05-27 07:00:24 +03:00
|
|
|
func (h *Hub) run() {
|
2013-10-16 20:41:47 +04:00
|
|
|
for {
|
|
|
|
select {
|
2016-05-27 07:00:24 +03:00
|
|
|
case conn := <-h.register:
|
|
|
|
h.connections[conn] = true
|
|
|
|
case conn := <-h.unregister:
|
|
|
|
if _, ok := h.connections[conn]; ok {
|
|
|
|
delete(h.connections, conn)
|
2016-05-18 17:57:16 +03:00
|
|
|
close(conn.send)
|
2014-06-28 00:08:22 +04:00
|
|
|
}
|
2016-05-27 07:00:24 +03:00
|
|
|
case message := <-h.broadcast:
|
|
|
|
for conn := range h.connections {
|
2013-10-16 20:41:47 +04:00
|
|
|
select {
|
2016-05-18 17:57:16 +03:00
|
|
|
case conn.send <- message:
|
2013-10-16 20:41:47 +04:00
|
|
|
default:
|
2016-05-18 17:57:16 +03:00
|
|
|
close(conn.send)
|
|
|
|
delete(hub.connections, conn)
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|