Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Feat/63] matching_not_found 로직 추가 #64

Merged
merged 1 commit into from
Sep 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions public/matching/scripts/socket.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,34 @@ function setUpMatchingSocketListeners() {
const timeoutId = setTimeout(() => {
// 2분 동안 "matching-found-sender" or "matching-found-receiver" 이벤트가 발생하지 않으면 매칭 재시작 요청
socket.emit("matching-retry", { priority: 50 });

// 3분 타이머 시작, matching_not_found
const timeoutIdforNotFound = setTimeout(()=>{
// matching_retry 이후 "matching-found-sender" or "matching-found-receiver" 이벤트가 발생하지 않을 경우 matching-not-found emit 전송
socket.emit("matching-not-found");

alert("매칭을 찾을 수 없습니다.");

window.location.href = "/";

},180000); // 180000ms = 3분
}, 120000); // 120000ms = 2분

timers.matchingRetryCallback = timeoutId;
timers.matchingNotFoundCallback = timeoutIdforNotFound;
console.log(timers);

});

// "matching-found-receiver" event listener : receiver socket
socket.on("matching-found-receiver", (response) => {
// 매칭 상대가 정해졌으므로, matchingRetry callback 취소
clearTimeout(timers.matchingRetryCallback);
delete timers.matchingRetryCallback;

// 매칭 상대가 정해졌으므로, matchingNotFound callback 취소
clearTimeout(timers.matchingNotFoundCallback);
delete timers.matchingNotFoundCallback;

// 13) matching-found-success emit
socket.emit("matching-found-success", { senderMemberId: response.data.memberId, gameMode: response.data.gameMode });
Expand Down Expand Up @@ -82,6 +99,10 @@ function setUpMatchingSocketListeners() {
clearTimeout(timers.matchingRetryCallback);
delete timers.matchingRetryCallback;

// 매칭 상대가 정해졌으므로, matchingNotFound callback 취소
clearTimeout(timers.matchingNotFoundCallback);
delete timers.matchingNotFoundCallback;

// 10초 타이머 시작, matchingSuccessSender call back
setTimeout(() => {
// 10초 이내에 matching-success-sender가 내 소켓에 도착했으면, 10초 후에 matching-success-final emit
Expand Down
35 changes: 34 additions & 1 deletion socket/handlers/matching/matchingHandler/matchingFoundHandler.js
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,37 @@ function deleteSocketFromMatching(socket, io, otherSocket, roomName) {
otherSocket.highestPriorityNode = null;
}

module.exports = { deleteSocketFromMatching };
/**
* 소켓 자신만을 매칭 풀에서 삭제 (room leave, priorityTree 제거 및 초기화)
* @param {*} socket
* @param {*} otherSocket
* @param {*} roomName
*/
function deleteMySocketFromMatching(socket, io, roomName) {
// 14) 소켓 룸에서 제거
socket.leave(roomName);

// 15) priorityTree에서 삭제
const room = io.sockets.adapter.rooms.get(roomName);

if (room) {
// 룸에 있는 각 소켓에 대해 콜백 함수 실행
room.forEach((socketId) => {
const roomSocket = io.sockets.sockets.get(socketId);
if (roomSocket) {
// roomSocket의 priorityTree에서 socket의 값을 지우기
roomSocket.priorityTree.removeByMemberId(socket.memberId);
}
});
} else {
console.log(`Room ${roomName} does not exist or is empty.`);
}

// 16) 각자의 priorityTree 삭제
socket.priorityTree.clear();

// 각자의 highestPriorityNode 삭제
socket.highestPriorityNode = null;
}

module.exports = { deleteSocketFromMatching, deleteMySocketFromMatching };
40 changes: 26 additions & 14 deletions socket/handlers/matching/matchingSocketListeners.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
const { fetchMatchingApi, matchingFoundApi, matchingSuccessApi } = require("../../apis/matchApi");
const { fetchMatchingApi, matchingFoundApi, matchingSuccessApi, updateMatchingStatusApi } = require("../../apis/matchApi");

const { updateOtherPriorityTrees, updatePriorityTree, handleSocketError, joinGameModeRoom, findMatching } = require("./matchingHandler/matchingStartedHandler");
const { isSocketActiveAndInRoom } = require("./matchingHandler/matchingCommonHandler");
const { deleteSocketFromMatching } = require("./matchingHandler/matchingFoundHandler");
const { deleteSocketFromMatching, deleteMySocketFromMatching } = require("./matchingHandler/matchingFoundHandler");

const { emitError } = require("../../emitters/errorEmitter");
const {
Expand All @@ -25,6 +25,7 @@ const { getSocketIdByMemberId } = require("../../common/memberSocketMapper");
async function setupMatchSocketListeners(socket, io) {
socket.on("matching-request", async (request) => {
const gameMode = request.gameMode;
socket.gameMode = request.gameMode;
const roomName = "GAMEMODE_" + gameMode;

// 2) socket.id가 소켓 룸 "GAMEMODE_" + gameMode에 있는지 확인
Expand Down Expand Up @@ -138,21 +139,32 @@ async function setupMatchSocketListeners(socket, io) {
console.log("member ID:", socket.memberId);
});

socket.on("matching_found", handleMatchingFound);
socket.on("matching_success", handleMatchingSuccess);
socket.on("matching_failed", handleMatchingFailed);
}
socket.on("matching-retry", (request) => {
console.log("================= matching_retry ======================");
console.log("member ID:", socket.memberId);
console.log("priority : ", request.priority);

function handleMatchingFound(request) {
console.log("matching_found", request);
}

function handleMatchingSuccess(request) {
console.log(request);
}
})

// Flow #22
socket.on("matching-not-found", async (request) => {
console.log("================= matching_not_found ======================");
// 14 ~ 16) room leave, 다른 socket들의 priorityTree에서 제거, 두 socket의 priorityTree 초기화
const roomName = "GAMEMODE_" + socket.gameMode;
deleteMySocketFromMatching(socket, io, roomName);

// 17) matching_status 변경
try{
const result = await updateMatchingStatusApi(socket, "FAIL");
if(result){
console.log("Matching Not Found 처리 완료");
}
}catch (error) {
handlerSocketError(socket, error);
}
})

function handleMatchingFailed(request) {
console.log(request);
}

module.exports = { setupMatchSocketListeners };
Loading