-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathhub.go
60 lines (49 loc) · 1015 Bytes
/
hub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
package main
import (
"golang.org/x/net/websocket"
"sync"
)
type Hub struct {
rooms map[string]*Room
mutex *sync.RWMutex
}
func NewHub() *Hub {
return &Hub{make(map[string]*Room), &sync.RWMutex{}}
}
func (h *Hub) HTTPHandler() websocket.Handler {
return websocket.Handler(h.connect)
}
func (h *Hub) Close() {
h.mutex.Lock()
defer h.mutex.Unlock()
for id, room := range h.rooms {
delete(h.rooms, id)
room.Close()
}
}
func (h *Hub) connect(ws *websocket.Conn) {
roomId := ws.Request().URL.Query().Get("room")
room := h.getOrCreateRoom(roomId)
conn := NewConn(ws, room)
room.Add(conn)
conn.Run()
room.Rm(conn)
h.cleanupRoom(roomId)
}
func (h *Hub) getOrCreateRoom(id string) *Room {
h.mutex.Lock()
defer h.mutex.Unlock()
if room, ok := h.rooms[id]; ok {
return room
}
room := NewRoom()
h.rooms[id] = room
return room
}
func (h *Hub) cleanupRoom(id string) {
h.mutex.Lock()
defer h.mutex.Unlock()
if room, ok := h.rooms[id]; ok && room.IsEmpty() {
delete(h.rooms, id)
}
}