Skip to content

Commit

Permalink
[BE] 소켓 연결 시 SID 확인 (#99)
Browse files Browse the repository at this point in the history
* chore:nodemon 설치

* feat: 소켓 연결 시 마스터, 참여자 sid확인

* chore: .env gitignore 추가

* refactor: 랜덤 포지션을 지정하는 함수 수정

* feat: getSocket 함수 transports에 websocket 추가

---------

Co-authored-by: dooohun <[email protected]>
  • Loading branch information
glaxyt and dooohun authored Nov 21, 2024
1 parent bf760cc commit 724089b
Show file tree
Hide file tree
Showing 20 changed files with 224 additions and 32 deletions.
95 changes: 95 additions & 0 deletions .pnp.cjs

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file added .yarn/cache/fsevents-patch-6b67494872-10c0.zip
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
2 changes: 2 additions & 0 deletions packages/client/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,5 @@ dist-ssr
*.sw?

*storybook.log

.env*
42 changes: 19 additions & 23 deletions packages/client/src/shared/utils/generateRandomPositions.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { toastController } from '@/features/toast/model/toastController';

interface Coordinates {
x: number;
y: number;
Expand All @@ -21,42 +23,36 @@ export function generateRandomPositions({
to,
count,
buttonSize,
spacing = 10,
}: GenerateRandomPositionsProps) {
const toast = toastController();
const positions: Coordinates[] = [];
const { x: fromX, y: fromY } = from;
const { x: toX, y: toY } = to;
const { width: buttonWidth, height: buttonHeight } = buttonSize;
const spacing = 5;

const isOverlap = (x: number, y: number) => {
return positions.some((position) => {
const isOverlap = (x: number, y: number, existingPositions: Coordinates[]) => {
return existingPositions.some((pos) => {
return (
x < position.x + buttonWidth + spacing &&
x + buttonWidth + spacing > position.x &&
y < position.y + buttonHeight + spacing &&
y + buttonHeight + spacing > position.y
x < pos.x + buttonSize.width + spacing &&
x + buttonSize.width + spacing > pos.x &&
y < pos.y + buttonSize.height + spacing &&
y + buttonSize.height + spacing > pos.y
);
});
};

let attempts = 0;
const maxAttempts = 100;

for (let i = 0; i < count; i++) {
let x, y;

let attempts = 0;
do {
x = Math.floor(Math.random() * (toX - fromX - buttonWidth - spacing) + fromX);
y = Math.floor(Math.random() * (toY - fromY - buttonHeight - spacing) + fromY);
x = Math.floor(Math.random() * (to.x - from.x - buttonSize.width - spacing)) + from.x;
y = Math.floor(Math.random() * (to.y - from.y - buttonSize.height - spacing)) + from.y;
attempts++;
} while (isOverlap(x, y, positions) && attempts < 100);

if (attempts >= maxAttempts) {
console.warn('최대 시도 횟수에 도달했습니다. 더 이상 충돌 없는 위치를 찾을 수 없습니다.');
break;
}
} while (isOverlap(x, y));

positions.push({ x, y });
if (attempts < 100) {
positions.push({ x, y });
} else {
toast.error('버튼을 배치할 수 없습니다.');
}
}

return positions;
Expand Down
6 changes: 5 additions & 1 deletion packages/client/src/shared/utils/socket.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { io, Socket } from 'socket.io-client';
import { getCookie } from './cookie';

let socket: Socket | null = null;

export function getQuizSocket(): Socket {
if (!socket) {
socket = io(`${import.meta.env.VITE_SERVER_URL}/game`);
socket = io(`${import.meta.env.VITE_SERVER_URL}/game`, {
auth: { sid: getCookie('sid') },
transports: ['websocket'],
});
}
return socket;
}
3 changes: 2 additions & 1 deletion packages/server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
"packageManager": "[email protected]",
"scripts": {
"start": "ts-node src/main.ts",
"start:dev": "ts-node-dev --respawn src/main.ts",
"start:dev": "nodemon --watch src --exec ts-node src/main.ts",
"build": "tsc",
"test": "jest",
"test:e2e": "jest --config ./test/jest-e2e.json"
Expand Down Expand Up @@ -41,6 +41,7 @@
"@types/node": "^22.8.7",
"@types/supertest": "^6.0.2",
"jest": "^29.7.0",
"nodemon": "^3.1.7",
"supertest": "^7.0.0",
"ts-jest": "^29.2.5",
"ts-node": "^10.9.2",
Expand Down
28 changes: 23 additions & 5 deletions packages/server/src/module/game/game.gateway.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,29 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
private readonly gameService: GameService,
) {}

// 클라이언트가 연결했을 때 처리하는 메서드
async handleConnection(client: Socket) {
console.log(`Client connected: ${client.id}`);
// 클라이언트의 인증 정보에서 SID 가져오기
const { sid } = client.handshake?.auth;
if (!sid) {
return;
}

// SID 타입 확인
const sidType = await this.gameService.checkSidType(sid);
const key = sidType.type === 'master' ? `master_sid=${sid}` : `participant_sid=${sid}`;

// Redis에서 데이터 가져오기
const data = await this.redisService.get(key);
if (data) {
const { pinCode } = JSON.parse(data);
client.join(pinCode); // Room에 소켓 추가

const gameInfoJson = await this.redisService.get(`gameId=${pinCode}`);
if (gameInfoJson) {
const gameInfo = JSON.parse(gameInfoJson);
client.emit('nickname', gameInfo.participantList);
}
}
}

// 클라이언트가 연결을 끊었을 때 처리하는 메서드
Expand Down Expand Up @@ -101,15 +121,13 @@ export class GameGateway implements OnGatewayConnection, OnGatewayDisconnect {
// 게임 현재 상태 가져오기
const gameInfo = JSON.parse(await this.redisService.get(`gameId=${pinCode}`));

const { classId, currentOrder, participantList } = gameInfo;
const { classId, currentOrder, quizMaxNum } = gameInfo;
// 캐싱된 퀴즈를 가져온다. 퀴즈를 생성할 경우, 만들어졌을거라 예상
// 만일 레디스에 퀴즈가 저장되어있지않다면, 퀴즈를 다시 캐싱해오는 로직이 필요할지도.
const quizData = JSON.parse(await this.redisService.get(`classId=${classId}`));

const currentQuizData = quizData[currentOrder];

// client.emit('show quiz', currentQuizData);
// client.to(pinCode).emit('show quiz', currentQuizData);
this.server.to(pinCode).emit('show quiz', currentQuizData);

// gameInfo.currentOrder += 1;
Expand Down
Loading

0 comments on commit 724089b

Please sign in to comment.