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

[#79] 웹 소켓 정상작동 시에 연결 #154

Merged
merged 3 commits into from
Nov 29, 2023
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
4 changes: 2 additions & 2 deletions frontend/src/components/Common/Loading.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,9 @@ export default function Loading({ size, color }: Props) {
cy="50"
fill="none"
stroke={color}
stroke-width="10"
strokeWidth="10"
r="35"
stroke-dasharray="164.93361431346415 56.97787143782138"
strokeDasharray="164.93361431346415 56.97787143782138"
>
<animateTransform
attributeName="transform"
Expand Down
10 changes: 6 additions & 4 deletions frontend/src/components/SocketTimer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,22 @@ interface Props {
socket: Socket;
isConnected: boolean;
endsAt: Date;
pingTime: number;
socketEvent: string;
onTimeout?: () => void;
}

export default function SocketTimer(props: Props) {
let { socket, endsAt, isConnected, onTimeout } = props;
// api 연결이 X endsAt 대신 임시로 만들어놓은 것.
// min 1 => 60초 동안 돌아갑니다. 변경해서 쓰세요 일단은..
let { socket, endsAt, isConnected, onTimeout, pingTime, socketEvent } = props;
// 대회 시간 검증이 안 되어 있어서, 끝나는 시간이 현재 시간보다 모두 전입니다. 그래서 지금 시간 기준으로 120분 더하고 마지막 시간이다라고 가정합니다.
const min = 120;
endsAt = new Date(new Date().getTime() + min * 60 * 1000);

const { remainMiliSeconds, isTimeout } = useSocketTimer({
socket,
endsAt,
socketEvent: 'ping',
socketEvent,
pingTime,
});

useEffect(() => {
Expand Down
58 changes: 28 additions & 30 deletions frontend/src/hooks/timer/useSocketTimer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,44 @@ interface Props {
socket: Socket;
endsAt: Date;
socketEvent: string;
pingTime: number;
}

export default function useSocketTimer({ socket, endsAt, socketEvent }: Props) {
export default function useSocketTimer({ socket, endsAt, socketEvent, pingTime }: Props) {
const timerIntervalId = useRef<NodeJS.Timeout | null>(null);
const pingIntervalId = useRef<NodeJS.Timeout | null>(null);

const endTime = useMemo(() => endsAt.getTime(), [endsAt]);
const [isTimeout, setIsTimeout] = useState(false);
const [remainMiliSeconds, setRemainMiliSeconds] = useState<number>(-1);

useEffect(() => {
console.log('타이머 실행');
// 웹 소켓 대신 사용.
mockWebSocket();
if (pingIntervalId.current) clearInterval(pingIntervalId.current);

socket.emit(socketEvent);
if (socket.hasListeners(socketEvent)) {
socket.on(socketEvent, handlePingMessage);
}
socket.on(socketEvent, handlePingMessage);

pingIntervalId.current = setInterval(() => {
socket.emit(socketEvent);
}, pingTime);
}, [socket]);

const handlePingMessage = useCallback((time: Date | string) => {
console.log(time);
if (timerIntervalId.current) clearInterval(timerIntervalId.current);

time = typeof time === 'string' ? new Date(time) : time;
const remainMiliSec = endTime - time.getTime();
setRemainMiliSeconds(remainMiliSec);
timerIntervalId.current = setInterval(() => {
setRemainMiliSeconds((prev) => prev - 1000);
}, 1000);
}, []);

// 웹 소켓 대신 사용.
// 웹 소켓 연결 후 삭제 예정
const mockWebSocket = useCallback(() => {
const delayFactor = 2000;
const serverTime = new Date();
handlePingMessage(serverTime);
setInterval(() => {
const serverTime = new Date();
handlePingMessage(serverTime);
}, 5000 + Math.random() * delayFactor);
}, []);
const handlePingMessage = useCallback(
(time: Date) => {
console.log('서버에서 온 시간 websocket 연결 확인 용', time);
Copy link
Collaborator

@dmdmdkdkr dmdmdkdkr Nov 29, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

console.log 이 부분은 지우지 않고 배포하게 되나요?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

�if (process.env.NODE_ENV === "production") { // production에서만 사용할 수 없도록
console = window.console || {};
console.log = function no_console() {}; // console log 막기
console.warn = function no_console() {}; // console warning 막기
console.error = function () {}; // console error 막기
}
이렇게하면 배포할 때, log가 안 찍히게 할 수 있네요.
웹소켓 연결을 대회 페이지에서 계속 확인해야 개발하기 편할 것 같아서 남겨두긴 했습니다.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

오오 신기하네요, 감사합니다!

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

� 왜 자꾸 이런게 생길까요 � <- ???

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

그러게요 마크다운에서 깨지는 문자가 있나봐요:

if (timerIntervalId.current) clearInterval(timerIntervalId.current);

time = typeof time === 'string' ? new Date(time) : time;

const remainMiliSec = endTime - time.getTime();
setRemainMiliSeconds(remainMiliSec);

timerIntervalId.current = setInterval(() => {
setRemainMiliSeconds((prev) => prev - 1000);
}, 1000);
},
[endTime],
);

useEffect(() => {
// 초기 값인 -1 => 서버에서 시간이 오지 않았다.
Expand All @@ -55,5 +52,6 @@ export default function useSocketTimer({ socket, endsAt, socketEvent }: Props) {
setIsTimeout(true);
}
}, [remainMiliSeconds]);

return { remainMiliSeconds, isTimeout };
}
4 changes: 4 additions & 0 deletions frontend/src/pages/ContestPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ import { isNil } from '@/utils/type';
const RUN_SIMULATION = '테스트 실행';
const CANCEL_SIMULATION = '실행 취소';
const DASHBOARD_URL = '/contest/dashboard';
const COMPEITION_PING_TIME = 5 * 1000;
const COMPEITION_SOCKET_EVENT = 'ping';

export default function ContestPage() {
const { id } = useParams<{ id: string }>();
Expand Down Expand Up @@ -107,6 +109,8 @@ export default function ContestPage() {
socket={socket.current}
isConnected={isConnected}
endsAt={new Date(endsAt)}
pingTime={COMPEITION_PING_TIME}
socketEvent={COMPEITION_SOCKET_EVENT}
onTimeout={handleTimeout}
/>
</section>
Expand Down
Loading