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
|
|
|
|
|
2018-04-16 06:20:28 +03:00
|
|
|
// Hub maintains the set of active clients and broadcasts messages to the
|
2016-07-19 02:08:34 +03:00
|
|
|
// clients.
|
2016-05-27 07:00:24 +03:00
|
|
|
type Hub struct {
|
2016-07-19 02:08:34 +03:00
|
|
|
// Registered clients.
|
|
|
|
clients map[*Client]bool
|
2013-10-16 20:41:47 +04:00
|
|
|
|
2016-07-19 02:08:34 +03:00
|
|
|
// Inbound messages from the clients.
|
2013-10-16 20:41:47 +04:00
|
|
|
broadcast chan []byte
|
|
|
|
|
2016-07-19 02:08:34 +03:00
|
|
|
// Register requests from the clients.
|
|
|
|
register chan *Client
|
2013-10-16 20:41:47 +04:00
|
|
|
|
2016-07-19 02:08:34 +03:00
|
|
|
// Unregister requests from clients.
|
|
|
|
unregister chan *Client
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
|
2016-07-19 02:08:34 +03:00
|
|
|
func newHub() *Hub {
|
|
|
|
return &Hub{
|
|
|
|
broadcast: make(chan []byte),
|
|
|
|
register: make(chan *Client),
|
|
|
|
unregister: make(chan *Client),
|
|
|
|
clients: make(map[*Client]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-07-19 02:08:34 +03:00
|
|
|
case client := <-h.register:
|
|
|
|
h.clients[client] = true
|
|
|
|
case client := <-h.unregister:
|
|
|
|
if _, ok := h.clients[client]; ok {
|
|
|
|
delete(h.clients, client)
|
|
|
|
close(client.send)
|
2014-06-28 00:08:22 +04:00
|
|
|
}
|
2016-05-27 07:00:24 +03:00
|
|
|
case message := <-h.broadcast:
|
2016-07-19 02:08:34 +03:00
|
|
|
for client := range h.clients {
|
2013-10-16 20:41:47 +04:00
|
|
|
select {
|
2016-07-19 02:08:34 +03:00
|
|
|
case client.send <- message:
|
2013-10-16 20:41:47 +04:00
|
|
|
default:
|
2016-07-19 02:08:34 +03:00
|
|
|
close(client.send)
|
|
|
|
delete(h.clients, client)
|
2013-10-16 20:41:47 +04:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|