websocket/examples/chat/hub.go

52 lines
1.2 KiB
Go
Raw Normal View History

// 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 {
case conn := <-hub.register:
hub.connections[conn] = true
case conn := <-hub.unregister:
if _, ok := hub.connections[conn]; ok {
delete(hub.connections, conn)
close(conn.send)
}
case message := <-hub.broadcast:
for conn := range hub.connections {
2013-10-16 20:41:47 +04:00
select {
case conn.send <- message:
2013-10-16 20:41:47 +04:00
default:
close(conn.send)
delete(hub.connections, conn)
2013-10-16 20:41:47 +04:00
}
}
}
}
}