-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHandleMessage.go
More file actions
424 lines (342 loc) · 9.12 KB
/
Copy pathHandleMessage.go
File metadata and controls
424 lines (342 loc) · 9.12 KB
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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
package main
import (
"strconv"
)
func (wss *WebsocketServer) isVaildRoomId(roomId int) bool {
wss.mu.RLock()
defer wss.mu.RUnlock()
if _, ok := wss.rooms[roomId]; ok {
return true
}
return false
}
func (wss *WebsocketServer) isVaildNick(roomId int, nick string) bool {
wss.mu.RLock()
defer wss.mu.RUnlock()
if room, ok := wss.rooms[roomId]; ok {
if _, ok := room.Clients[nick]; ok {
return true
}
}
return false
}
// sendInTheRoom 방에 있는 사용자에게 메시지를 보낸다.
func (wss *WebsocketServer) sendInTheRoom(roomId int, msg *Message) {
wss.mu.RLock()
room, ok := wss.rooms[roomId]
wss.mu.RUnlock()
if !ok {
return
}
for _, client := range room.Clients {
client.send <- msg
}
}
// sendInTheRoomExceptSender Sender를 제외한 방에 있는 사용자에게 메시지를 보낸다.
func (wss *WebsocketServer) sendInTheRoomExceptSender(roomId int, msg *Message) {
wss.mu.RLock()
room, ok := wss.rooms[roomId]
wss.mu.RUnlock()
if !ok {
return
}
for _, client := range room.Clients {
if client.Nick != msg.Sender {
client.send <- msg
}
}
}
// setNick 닉네임을 변경한다.
func (wss *WebsocketServer) setNick(msg *Message) {
// 기존과 같은 닉네임이면 변경하지 않는다.
if msg.Sender == msg.Data {
return
}
// nick 중복 체크
wss.mu.RLock()
for _, room := range wss.rooms {
for nick := range room.Clients {
if nick == msg.Data {
wss.mu.RUnlock()
Manager.mu.RLock()
player := Manager.players[msg.Sender]
Manager.mu.RUnlock()
if player != nil {
player.Client.send <- &Message{Action: "error", Data: "nick duplicate"}
}
return
}
}
}
wss.mu.RUnlock()
// 닉네임 변경
wss.mu.Lock()
client := wss.rooms[msg.RoomId].Clients[msg.Sender]
client.Nick = msg.Data
wss.rooms[msg.RoomId].Clients[client.Nick] = client
delete(wss.rooms[msg.RoomId].Clients, msg.Sender)
// 방장이면 owner도 변경
if wss.rooms[msg.RoomId].Owner == msg.Sender {
wss.rooms[msg.RoomId].Owner = msg.Data
}
wss.mu.Unlock()
// manager도 변경
Manager.mu.Lock()
Manager.players[msg.Data] = Manager.players[msg.Sender]
delete(Manager.players, msg.Sender)
Manager.mu.Unlock()
// 방에 입장한 사용자에게 보내기
wss.sendInTheRoom(msg.RoomId, msg)
}
// newJoinRoom 방 생성, 입장 처리
func (wss *WebsocketServer) newJoinRoom(msg *Message) {
roomId := -1
Manager.mu.RLock()
player, ok := Manager.players[msg.Sender]
Manager.mu.RUnlock()
if !ok {
Error.Println(msg.Sender, " player not found")
return
}
oldRoomId := player.RoomId
if msg.Action == "new-room" {
// 새로운 방을 생성한다.
roomId = wss.getFreeRoomID()
if roomId == -1 {
Error.Println("room id not found")
return
}
wss.mu.Lock()
wss.rooms[roomId] = NewRoomInfo(roomId, player.Client, "room "+strconv.Itoa(roomId))
wss.mu.Unlock()
} else {
// 방에 입장한다.
roomId, _ = strconv.Atoi(msg.Data)
}
// 개임을 생성한다.
Manager.NewGame(roomId, player.Client)
if !wss.OutRoom(oldRoomId, msg.Sender) {
Error.Printf("[newJoinRoom] out room fail, roomID:%d, user:%s", oldRoomId, msg.Sender)
}
if !wss.InRoom(roomId, msg.Sender) {
Error.Printf("[newJoinRoom] in room fail, roomID:%d, user:%s", roomId, msg.Sender)
}
wss.RefreshWaitingRoom()
}
func (wss *WebsocketServer) InRoom(roomId int, nick string) bool {
Manager.mu.RLock()
player, ok := Manager.players[nick]
Manager.mu.RUnlock()
if !ok {
Error.Println(nick, " player not found")
return false
}
player.RoomId = roomId
wss.mu.Lock()
wss.rooms[roomId].Clients[nick] = player.Client
wss.mu.Unlock()
// 방에 입장한 사용자에게 보내기
msg := &Message{
Action: "join-room",
RoomId: roomId,
Sender: nick}
wss.mu.RLock()
msg.RoomList = appendRoomInfo(msg.RoomList, wss.rooms[roomId])
roomState := wss.rooms[roomId].GetState()
wss.mu.RUnlock()
wss.sendInTheRoom(roomId, msg)
// 이미 play 중이면 옵져버 상태로 설정
if roomState == "playing" {
player.Client.Game.Ch <- &Message{Action: "observer"}
}
return true
}
func (wss *WebsocketServer) OutRoom(roomId int, nick string) bool {
wss.mu.Lock()
room, ok := wss.rooms[roomId]
if !ok {
wss.mu.Unlock()
Error.Println("room not found, roomID:", roomId)
return false
}
delete(room.Clients, nick)
clientCount := len(room.Clients)
if roomId != WAITITNG_ROOM && clientCount == 0 {
// delete room
delete(wss.rooms, roomId)
wss.mu.Unlock()
} else {
// change owner
newOwner := room.Owner
if room.Owner == nick {
// 첫 번째 클라이언트를 새 방장으로 지정 (맵 순회 순서는 무작위지만 일단 하나 선택)
for _, client := range room.Clients {
newOwner = client.Nick
break
}
if newOwner == nick && roomId == WAITITNG_ROOM {
newOwner = ""
}
room.Owner = newOwner
}
roomState := room.State
wss.mu.Unlock()
// 방에 입장한 사용자에게 보내기
msg := &Message{
Action: "leave-room",
RoomId: roomId,
Sender: nick}
wss.mu.RLock()
msg.RoomList = appendRoomInfo(msg.RoomList, wss.rooms[roomId])
wss.mu.RUnlock()
wss.sendInTheRoom(msg.RoomId, msg)
// 게임 오버 전파
client := Manager.getClient(nick)
if roomId != WAITITNG_ROOM && roomState == "playing" && client != nil && client.Game != nil && client.Game.IsPlaying() {
msg.Action = "over-game"
Manager.overGame(msg)
}
}
return true
}
func (wss *WebsocketServer) RefreshWaitingRoom() {
msg := &Message{
Action: "list-room",
RoomId: WAITITNG_ROOM,
Sender: "server"}
msg.RoomList = wss.getAllRoomInfo()
wss.sendInTheRoom(WAITITNG_ROOM, msg)
}
// leaveRoom 방 나가기 처리
func (wss *WebsocketServer) leaveRoom(msg *Message) {
client := Manager.getClient(msg.Sender)
if client == nil {
Error.Println(msg.Sender, " player not found, roomID:", msg.RoomId)
return
}
// 게임 중이면 종료
if client.Game.IsPlaying() {
client.Game.Ch <- &Message{
Action: "stop-game",
}
}
// 방에서 나가기
if !wss.OutRoom(msg.RoomId, msg.Sender) {
Error.Printf("[leaveRoom] out room fail, roomID:%d, user:%s", msg.RoomId, msg.Sender)
}
// 대기실로 이동
if !wss.InRoom(WAITITNG_ROOM, msg.Sender) {
Error.Printf("[leaveRoom] in room fail, roomID:%d, user:%s", WAITITNG_ROOM, msg.Sender)
}
wss.RefreshWaitingRoom()
}
func (wss *WebsocketServer) getAllRoomInfo() []RoomInfo {
wss.mu.RLock()
defer wss.mu.RUnlock()
roomList := make([]RoomInfo, 0, len(wss.rooms))
for _, roomInfo := range wss.rooms {
roomList = appendRoomInfo(roomList, roomInfo)
}
return roomList
}
// listRoom 방 목록 보기 처리
func (wss *WebsocketServer) listRoom(msg *Message) {
msg.RoomList = wss.getAllRoomInfo()
// 요청한 사용자에게 보내기
wss.mu.RLock()
room, ok := wss.rooms[msg.RoomId]
wss.mu.RUnlock()
if ok {
client := room.Clients[msg.Sender]
if client != nil {
client.send <- msg
}
}
}
func (wss *WebsocketServer) listRank(msg *Message) {
count, err := strconv.Atoi(msg.Data)
if err != nil {
Error.Println("listRank count error:", err, msg.Data)
count = 5
}
if count <= 0 {
count = 5
}
msg.RankList = Manager.getRankList(count)
if msg.RankList != nil && len(msg.RankList) > 0 {
wss.mu.RLock()
room, ok := wss.rooms[msg.RoomId]
wss.mu.RUnlock()
if ok {
client := room.Clients[msg.Sender]
if client != nil {
client.send <- msg
}
}
}
}
func (wss *WebsocketServer) startGame(msg *Message) {
wss.mu.RLock()
room, ok := wss.rooms[msg.RoomId]
wss.mu.RUnlock()
if !ok {
return
}
for _, client := range room.Clients {
if client.Game != nil {
client.Game.Start()
}
}
}
// actionGame 게임 동작 처리: "block-drop", "block-rotate", "block-left", "block-right", "block-down"
func (wss *WebsocketServer) actionGame(msg *Message) {
game := Manager.getGame(msg.Sender)
if game == nil {
Warning.Println("Unknown player:", msg.Sender)
return
}
if !game.IsPlaying() {
Warning.Println("Not playing:", msg.Sender)
return
}
Debug.Println("actionGame s:", msg.Action, msg.Sender, len(game.Ch))
game.Ch <- msg
Debug.Println("actionGame e:", msg.Action, msg.Sender, len(game.Ch))
}
// addBot 봇 추가
func (wss *WebsocketServer) addBot(msg *Message) {
// BotFather에게 봇 추가 요청
BotFather.fromManager <- msg
}
// HandleMessage websocket clinet -> server의 메시지를 처리한다.
func (wss *WebsocketServer) HandleMessage(msg *Message) {
Trace.Println("HandleMessage:", msg.Action, msg.Sender)
if !wss.isVaildRoomId(msg.RoomId) || !wss.isVaildNick(msg.RoomId, msg.Sender) {
Error.Println("Invalid RoomId or Nick:", msg)
return
}
switch msg.Action {
case "set-nick":
wss.setNick(msg)
case "new-room", "join-room":
wss.newJoinRoom(msg)
case "leave-room":
wss.leaveRoom(msg)
case "list-room":
wss.listRoom(msg)
case "list-rank":
wss.listRank(msg)
case "over-game", "sync-game", "end-game":
wss.sendInTheRoom(msg.RoomId, msg)
case "gift-full-blocks":
wss.sendInTheRoomExceptSender(msg.RoomId, msg)
case "start-game":
wss.startGame(msg)
case "block-drop", "block-rotate", "block-left", "block-right", "block-down":
wss.actionGame(msg)
case "add-bot":
wss.addBot(msg)
default:
Warning.Println("Unknown Action:", msg)
}
}