websocket/examples/chat/hub.go

52 lines
1.1 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 {
2013-10-16 20:41:47 +04:00
// Registered connections.
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.
register chan *Conn
2013-10-16 20:41:47 +04:00
// Unregister requests from connections.
unregister chan *Conn
2013-10-16 20:41:47 +04:00
}
var hub = Hub{
2013-10-16 20:41:47 +04:00
broadcast: make(chan []byte),
register: make(chan *Conn),
unregister: make(chan *Conn),
connections: make(map[*Conn]bool),
2013-10-16 20:41:47 +04:00
}
func (h *Hub) run() {
2013-10-16 20:41:47 +04:00
for {
select {
case conn := <-h.register:
h.connections[conn] = true
case conn := <-h.unregister:
if _, ok := h.connections[conn]; ok {
delete(h.connections, conn)
close(conn.send)
}
case message := <-h.broadcast:
for conn := range h.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)
2016-07-11 07:15:05 +03:00
delete(h.connections, conn)
2013-10-16 20:41:47 +04:00
}
}
}
}
}