Skip to content

Commit 41864be

Browse files
committed
♻️ 소켓 연결 전 validation 체크 + enter 로직으로 변경
1 parent 0ba0181 commit 41864be

File tree

4 files changed

+68
-50
lines changed

4 files changed

+68
-50
lines changed

backend/src/main/java/io/f1/backend/domain/game/api/RoomController.java

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -31,10 +31,10 @@ public RoomCreateResponse saveRoom(@RequestBody @Valid RoomCreateRequest request
3131
return roomService.saveRoom(request);
3232
}
3333

34-
@PostMapping("/validation")
34+
@PostMapping("/enterRoom")
3535
@ResponseStatus(HttpStatus.NO_CONTENT)
3636
public void validateRoom(@RequestBody @Valid RoomValidationRequest request) {
37-
roomService.validateRoom(request);
37+
roomService.enterRoom(request);
3838
}
3939

4040
@GetMapping

backend/src/main/java/io/f1/backend/domain/game/app/RoomService.java

Lines changed: 60 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@
3434

3535
import lombok.RequiredArgsConstructor;
3636

37+
import org.hibernate.boot.model.naming.IllegalIdentifierException;
3738
import org.springframework.context.ApplicationEventPublisher;
3839
import org.springframework.stereotype.Service;
3940

@@ -73,95 +74,101 @@ public RoomCreateResponse saveRoom(RoomCreateRequest request) {
7374
return new RoomCreateResponse(newId);
7475
}
7576

76-
public void validateRoom(RoomValidationRequest request) {
77+
public void enterRoom(RoomValidationRequest request) {
7778

78-
Room room =
79-
roomRepository
80-
.findRoom(request.roomId())
81-
.orElseThrow(() -> new IllegalArgumentException("404 존재하지 않는 방입니다.-1"));
79+
Room room = findRoom(request.roomId());
8280

8381
if (room.getState().equals(RoomState.PLAYING)) {
8482
throw new IllegalArgumentException("403 게임이 진행중입니다.");
8583
}
8684

8785
int maxUserCnt = room.getRoomSetting().maxUserCount();
88-
int currentCnt = room.getPlayerSessionMap().size();
86+
int currentCnt = room.getUserIdSessionMap().size();
8987
if (maxUserCnt == currentCnt) {
9088
throw new IllegalArgumentException("403 정원이 모두 찼습니다.");
9189
}
9290

9391
if (room.getRoomSetting().locked()
94-
&& !room.getRoomSetting().password().equals(request.password())) {
92+
&& !room.getRoomSetting().password().equals(request.password())) {
9593
throw new IllegalArgumentException("401 비밀번호가 일치하지 않습니다.");
9694
}
95+
96+
room.getUserIdSessionMap().put(getCurrentUserId(), null);
9797
}
9898

99-
public RoomInitialData enterRoom(Long roomId, String sessionId) {
99+
public RoomInitialData initializeRoomSocket(Long roomId, String sessionId) {
100100

101-
Room room =
102-
roomRepository
103-
.findRoom(roomId)
104-
.orElseThrow(() -> new IllegalArgumentException("404 존재하지 않는 방입니다."));
101+
Room room = findRoom(roomId);
105102

106103
Player player = createPlayer();
107104

108105
Map<String, Player> playerSessionMap = room.getPlayerSessionMap();
106+
Map<Long, String> userIdSessionMap = room.getUserIdSessionMap();
109107

110108
playerSessionMap.put(sessionId, player);
109+
userIdSessionMap.put(roomId, sessionId);
111110

112111
RoomSettingResponse roomSettingResponse = toRoomSettingResponse(room);
113112

114113
Long quizId = room.getGameSetting().getQuizId();
115114
Quiz quiz = quizService.getQuizById(quizId);
116115

117116
GameSettingResponse gameSettingResponse =
118-
toGameSettingResponse(room.getGameSetting(), quiz);
117+
toGameSettingResponse(room.getGameSetting(), quiz);
119118

120119
PlayerListResponse playerListResponse = toPlayerListResponse(room);
121120

122121
SystemNoticeResponse systemNoticeResponse = ofPlayerEvent(player, RoomEventType.ENTER);
123122

124123
return new RoomInitialData(
125-
getDestination(roomId),
126-
roomSettingResponse,
127-
gameSettingResponse,
128-
playerListResponse,
129-
systemNoticeResponse);
124+
getDestination(roomId),
125+
roomSettingResponse,
126+
gameSettingResponse,
127+
playerListResponse,
128+
systemNoticeResponse);
130129
}
131130

132131
public RoomExitData exitRoom(Long roomId, String sessionId) {
133-
Room room =
134-
roomRepository
135-
.findRoom(roomId)
136-
.orElseThrow(() -> new IllegalArgumentException("404 존재하지 않는 방입니다."));
132+
Room room = findRoom(roomId);
137133

138134
Map<String, Player> playerSessionMap = room.getPlayerSessionMap();
139135

140136
String destination = getDestination(roomId);
141137

142-
if (playerSessionMap.size() == 1 && playerSessionMap.get(sessionId) != null) {
138+
Player removePlayer = playerSessionMap.get(sessionId);
139+
140+
// if (removePlayer == null) {
141+
// room.getUserIdSessionMap().remove(getCurrentUserId());
142+
// throw new IllegalIdentifierException("404 세션 없음 비정상적인 퇴장 요청");
143+
// }
144+
145+
/* 방 삭제 */
146+
if (playerSessionMap.size() == 1 && playerSessionMap.containsKey(sessionId)) {
143147
roomRepository.removeRoom(roomId);
144148
return RoomExitData.builder().destination(destination).removedRoom(true).build();
145149
}
146150

147-
Player removedPlayer = playerSessionMap.remove(sessionId);
148-
if (removedPlayer == null) {
149-
throw new IllegalArgumentException("퇴장 처리 불가 - 404 해당 세션 플레이어는 존재하지않습니다.");
150-
}
151+
/* 방장 변경 */
152+
if (room.getHost().getId().equals(removePlayer.getId())) {
153+
154+
Optional<String> nextHostSessionId = playerSessionMap.keySet().stream()
155+
.filter(key -> !key.equals(sessionId)).findFirst();
151156

152-
if (room.getHost().getId().equals(removedPlayer.getId())) {
153-
Optional<String> nextHostSessionId = playerSessionMap.keySet().stream().findFirst();
154157
Player nextHost =
155-
playerSessionMap.get(
156-
nextHostSessionId.orElseThrow(
157-
() ->
158-
new IllegalArgumentException(
159-
"방장 교체 불가 - 404 해당 세션 플레이어는 존재하지않습니다.")));
158+
playerSessionMap.get(
159+
nextHostSessionId.orElseThrow(
160+
() ->
161+
new IllegalArgumentException(
162+
"방장 교체 불가 - 404 해당 세션 플레이어는 존재하지않습니다.")));
163+
160164
room.updateHost(nextHost);
161165
}
162166

167+
room.getUserIdSessionMap().remove(removePlayer.getId());
168+
playerSessionMap.remove(sessionId);
169+
163170
SystemNoticeResponse systemNoticeResponse =
164-
ofPlayerEvent(removedPlayer, RoomEventType.EXIT);
171+
ofPlayerEvent(removePlayer, RoomEventType.EXIT);
165172

166173
PlayerListResponse playerListResponse = toPlayerListResponse(room);
167174

@@ -171,23 +178,31 @@ public RoomExitData exitRoom(Long roomId, String sessionId) {
171178
public RoomListResponse getAllRooms() {
172179
List<Room> rooms = roomRepository.findAll();
173180
List<RoomResponse> roomResponses =
174-
rooms.stream()
175-
.map(
176-
room -> {
177-
Long quizId = room.getGameSetting().getQuizId();
178-
Quiz quiz = quizService.getQuizById(quizId);
179-
180-
return toRoomResponse(room, quiz);
181-
})
182-
.toList();
181+
rooms.stream()
182+
.map(
183+
room -> {
184+
Long quizId = room.getGameSetting().getQuizId();
185+
Quiz quiz = quizService.getQuizById(quizId);
186+
187+
return toRoomResponse(room, quiz);
188+
})
189+
.toList();
183190
return new RoomListResponse(roomResponses);
184191
}
185192

186193
private static String getDestination(Long roomId) {
187194
return "/sub/room/" + roomId;
188195
}
189196

190-
private static Player createPlayer() {
197+
private Player createPlayer() {
191198
return new Player(getCurrentUserId(), getCurrentUserNickname());
192199
}
200+
201+
private Room findRoom(Long roomId) {
202+
return roomRepository
203+
.findRoom(roomId)
204+
.orElseThrow(() -> new IllegalArgumentException("404 존재하지 않는 방입니다."));
205+
}
206+
207+
193208
}

backend/src/main/java/io/f1/backend/domain/game/model/Room.java

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,13 +27,16 @@ public class Room {
2727

2828
private Map<String, Player> playerSessionMap = new ConcurrentHashMap<>();
2929

30+
private Map<Long,String> userIdSessionMap = new ConcurrentHashMap<>();
31+
3032
private final LocalDateTime createdAt = LocalDateTime.now();
3133

3234
public Room(Long id, RoomSetting roomSetting, GameSetting gameSetting, Player host) {
3335
this.id = id;
3436
this.roomSetting = roomSetting;
3537
this.gameSetting = gameSetting;
3638
this.host = host;
39+
3740
}
3841

3942
public void updateHost(Player nextHost) {

backend/src/main/java/io/f1/backend/domain/game/websocket/GameSocketController.java

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@ public class GameSocketController {
2020
private final MessageSender messageSender;
2121
private final RoomService roomService;
2222

23-
@MessageMapping("/room/enter/{roomId}")
24-
public void roomEnter(@DestinationVariable Long roomId, Message<?> message) {
23+
@MessageMapping("/room/initializeRoomSocket/{roomId}")
24+
public void initializeRoomSocket(@DestinationVariable Long roomId, Message<?> message) {
2525

2626
String websocketSessionId = getSessionId(message);
2727

28-
RoomInitialData roomInitialData = roomService.enterRoom(roomId, websocketSessionId);
28+
RoomInitialData roomInitialData = roomService.initializeRoomSocket(roomId, websocketSessionId);
2929
String destination = roomInitialData.destination();
3030

3131
messageSender.send(

0 commit comments

Comments
 (0)