first successful export
This commit is contained in:
15
ws/hub.go
15
ws/hub.go
@@ -1,7 +1,5 @@
|
||||
package ws
|
||||
|
||||
import "sync"
|
||||
|
||||
// Client represents a single WebSocket connection.
|
||||
// The handler owns the actual *websocket.Conn; the hub only needs the send channel.
|
||||
type Client struct {
|
||||
@@ -10,7 +8,6 @@ type Client struct {
|
||||
|
||||
// Hub manages all active clients and routes broadcast messages to them.
|
||||
type Hub struct {
|
||||
mu sync.Mutex
|
||||
clients map[*Client]struct{}
|
||||
Register chan *Client
|
||||
Unregister chan *Client
|
||||
@@ -19,10 +16,10 @@ type Hub struct {
|
||||
|
||||
func NewHub() *Hub {
|
||||
return &Hub{
|
||||
clients: make(map[*Client]struct{}),
|
||||
Register: make(chan *Client, 8),
|
||||
clients: make(map[*Client]struct{}),
|
||||
Register: make(chan *Client, 8),
|
||||
Unregister: make(chan *Client, 8),
|
||||
broadcast: make(chan []byte, 512),
|
||||
broadcast: make(chan []byte, 512),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,20 +27,15 @@ func (h *Hub) Run() {
|
||||
for {
|
||||
select {
|
||||
case c := <-h.Register:
|
||||
h.mu.Lock()
|
||||
h.clients[c] = struct{}{}
|
||||
h.mu.Unlock()
|
||||
|
||||
case c := <-h.Unregister:
|
||||
h.mu.Lock()
|
||||
if _, ok := h.clients[c]; ok {
|
||||
delete(h.clients, c)
|
||||
close(c.Send)
|
||||
}
|
||||
h.mu.Unlock()
|
||||
|
||||
case msg := <-h.broadcast:
|
||||
h.mu.Lock()
|
||||
for c := range h.clients {
|
||||
select {
|
||||
case c.Send <- msg:
|
||||
@@ -52,7 +44,6 @@ func (h *Hub) Run() {
|
||||
close(c.Send)
|
||||
}
|
||||
}
|
||||
h.mu.Unlock()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user