forked from kodestan/tank-ops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hub.go
65 lines (54 loc) · 1.04 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
59
60
61
62
63
64
65
package main
import (
"fmt"
"net/http"
"github.com/gorilla/websocket"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type RoomRequest struct {
code string
chans RoomChans
}
type Hub struct {
roomRequests chan RoomRequest
}
func NewHub() *Hub {
return &Hub{make(chan RoomRequest)}
}
func (h *Hub) Run() {
rooms := make(map[string]*Room)
closeReq := make(chan string)
for {
select {
case msg := <-h.roomRequests:
room, ok := rooms[msg.code]
if !ok {
room = NewRoom(msg.code, closeReq)
go room.Run()
rooms[msg.code] = room
}
room.requests <- msg
case code := <-closeReq:
room, ok := rooms[code]
if !ok {
fmt.Println("illegal")
break
}
close(room.requests)
delete(rooms, code)
}
}
}
func (h *Hub) ServeWs(w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
fmt.Println("hub: conn error")
return
}
player := NewPlayer(conn, h.roomRequests)
fmt.Println("start player goroutine")
go player.Run()
}