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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
|
package main
import (
"log"
"net/http"
"time"
"github.com/gorilla/websocket"
)
type GameHub struct {
game *Game
clients map[*GameClient]bool
receive chan *MessageWithClient
register chan *GameClient
unregister chan *GameClient
watchers map[*GameWatcher]bool
registerWatcher chan *GameWatcher
unregisterWatcher chan *GameWatcher
state int
finishTime time.Time
}
func NewGameHub(game *Game) *GameHub {
return &GameHub{
game: game,
clients: make(map[*GameClient]bool),
receive: make(chan *MessageWithClient),
register: make(chan *GameClient),
unregister: make(chan *GameClient),
watchers: make(map[*GameWatcher]bool),
registerWatcher: make(chan *GameWatcher),
unregisterWatcher: make(chan *GameWatcher),
state: 0,
}
}
func (h *GameHub) Run() {
ticker := time.NewTicker(10 * time.Second)
defer func() {
ticker.Stop()
}()
for {
select {
case client := <-h.register:
h.clients[client] = true
log.Printf("client registered: %d", len(h.clients))
case client := <-h.unregister:
if _, ok := h.clients[client]; ok {
h.closeClient(client)
}
log.Printf("client unregistered: %d", len(h.clients))
if len(h.clients) == 0 {
h.Close()
return
}
case watcher := <-h.registerWatcher:
h.watchers[watcher] = true
log.Printf("watcher registered: %d", len(h.watchers))
case watcher := <-h.unregisterWatcher:
if _, ok := h.watchers[watcher]; ok {
h.closeWatcher(watcher)
}
log.Printf("watcher unregistered: %d", len(h.watchers))
case message := <-h.receive:
log.Printf("received message: %s", message.Message.Type)
switch message.Message.Type {
case "connect":
if h.state == 0 {
h.state = 1
} else if h.state == 1 {
h.state = 2
for client := range h.clients {
client.send <- &Message{Type: "prepare", Data: MessageDataPrepare{Problem: "1 から 100 までの FizzBuzz を実装せよ (終端を含む)。"}}
}
} else {
log.Printf("invalid state: %d", h.state)
h.closeClient(message.Client)
}
case "ready":
if h.state == 2 {
h.state = 3
} else if h.state == 3 {
h.state = 4
for client := range h.clients {
client.send <- &Message{Type: "start", Data: MessageDataStart{StartTime: time.Now().Add(10 * time.Second).UTC().Format(time.RFC3339)}}
}
h.finishTime = time.Now().Add(3 * time.Minute)
} else {
log.Printf("invalid state: %d", h.state)
h.closeClient(message.Client)
}
case "code":
if h.state == 4 {
code := message.Message.Data.(MessageDataCode).Code
message.Client.code = code
message.Client.send <- &Message{Type: "score", Data: MessageDataScore{Score: 100}}
if message.Client.score == nil {
message.Client.score = new(int)
}
*message.Client.score = 100
var scoreA, scoreB *int
var codeA, codeB string
for client := range h.clients {
if client.team == "a" {
scoreA = client.score
codeA = client.code
} else {
scoreB = client.score
codeB = client.code
}
}
for watcher := range h.watchers {
watcher.send <- &Message{
Type: "watch",
Data: MessageDataWatch{
Problem: "1 から 100 までの FizzBuzz を実装せよ (終端を含む)。",
ScoreA: scoreA,
CodeA: codeA,
ScoreB: scoreB,
CodeB: codeB,
},
}
}
} else {
log.Printf("invalid state: %d", h.state)
h.closeClient(message.Client)
}
default:
log.Printf("unknown message type: %s", message.Message.Type)
h.closeClient(message.Client)
}
case <-ticker.C:
log.Printf("state: %d", h.state)
if h.state == 4 {
if time.Now().After(h.finishTime) {
h.state = 5
clientAndScores := make(map[*GameClient]*int)
for client := range h.clients {
clientAndScores[client] = client.score
}
for client, score := range clientAndScores {
var opponentScore *int
for c2, s2 := range clientAndScores {
if c2 != client {
opponentScore = s2
break
}
}
client.send <- &Message{Type: "finish", Data: MessageDataFinish{YourScore: score, OpponentScore: opponentScore}}
}
}
}
}
}
}
func (h *GameHub) Close() {
for client := range h.clients {
h.closeClient(client)
}
close(h.receive)
close(h.register)
close(h.unregister)
for watcher := range h.watchers {
h.closeWatcher(watcher)
}
close(h.registerWatcher)
close(h.unregisterWatcher)
}
func (h *GameHub) closeClient(client *GameClient) {
delete(h.clients, client)
close(client.send)
}
func (h *GameHub) closeWatcher(watcher *GameWatcher) {
delete(h.watchers, watcher)
close(watcher.send)
}
const (
writeWait = 10 * time.Second
pongWait = 60 * time.Second
pingPeriod = (pongWait * 9) / 10
maxMessageSize = 512
)
var (
newline = []byte{'\n'}
space = []byte{' '}
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type GameClient struct {
hub *GameHub
conn *websocket.Conn
send chan *Message
score *int
code string
team string
}
type GameWatcher struct {
hub *GameHub
conn *websocket.Conn
send chan *Message
}
// Receives messages from the client and sends them to the hub.
func (c *GameClient) readPump() {
defer func() {
log.Printf("closing client")
c.hub.unregister <- c
c.conn.Close()
}()
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
for {
var message Message
err := c.conn.ReadJSON(&message)
if err != nil {
log.Printf("error: %v", err)
return
}
c.hub.receive <- &MessageWithClient{c, &message}
}
}
// Receives messages from the hub and sends them to the client.
func (c *GameClient) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
err := c.conn.WriteJSON(message)
if err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
func serveWs(hub *GameHub, w http.ResponseWriter, r *http.Request, team string) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
client := &GameClient{hub: hub, conn: conn, send: make(chan *Message), team: team}
client.hub.register <- client
go client.writePump()
go client.readPump()
}
func serveWsWatcher(hub *GameHub, w http.ResponseWriter, r *http.Request) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
watcher := &GameWatcher{hub: hub, conn: conn, send: make(chan *Message)}
watcher.hub.registerWatcher <- watcher
go watcher.writePump()
go watcher.readPump()
}
// Receives messages from the client and sends them to the hub.
func (c *GameWatcher) readPump() {
c.conn.SetReadLimit(maxMessageSize)
c.conn.SetReadDeadline(time.Now().Add(pongWait))
c.conn.SetPongHandler(func(string) error { c.conn.SetReadDeadline(time.Now().Add(pongWait)); return nil })
}
// Receives messages from the hub and sends them to the client.
func (c *GameWatcher) writePump() {
ticker := time.NewTicker(pingPeriod)
defer func() {
ticker.Stop()
c.conn.Close()
log.Printf("closing watcher")
c.hub.unregisterWatcher <- c
}()
for {
select {
case message, ok := <-c.send:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if !ok {
c.conn.WriteMessage(websocket.CloseMessage, []byte{})
return
}
err := c.conn.WriteJSON(message)
if err != nil {
return
}
case <-ticker.C:
c.conn.SetWriteDeadline(time.Now().Add(writeWait))
if err := c.conn.WriteMessage(websocket.PingMessage, nil); err != nil {
return
}
}
}
}
|