-
Notifications
You must be signed in to change notification settings - Fork 2
/
hub.go
58 lines (50 loc) · 1.18 KB
/
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
package main
import (
"github.com/gorilla/mux"
"github.com/gorilla/websocket"
"log"
"net/http"
)
/* Controls a bunch of rooms */
type Hub struct {
hub map[string]*Room
upgrader websocket.Upgrader
}
/* If room doesn't exist creates it then returns it */
func (h *Hub) GetRoom(name string) *Room {
if _, ok := h.hub[name]; !ok {
h.hub[name] = NewRoom(name)
}
return h.hub[name]
}
/* Get ws conn. and hands it over to correct room */
func (h *Hub) HandleWS(w http.ResponseWriter, r *http.Request) {
params := mux.Vars(r)
room_name := params["room"]
c, err := h.upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println("upgrade:", err)
return
}
defer c.Close()
room := h.GetRoom(room_name)
id := room.Join(c)
/* Reads from the client's out bound channel and broadcasts it */
go room.HandleMsg(id)
/* Reads from client and if this loop breaks then client disconnected. */
room.clients[id].ReadLoop()
room.Leave(id)
}
/* Constructor */
func NewHub() *Hub {
hub := new(Hub)
hub.hub = make(map[string]*Room)
hub.upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
CheckOrigin: func(r *http.Request) bool {
return true
},
}
return hub
}