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 2 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
4 changes: 2 additions & 2 deletions frontend/src/components/SocketTimer/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ interface Props {

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

const { remainMiliSeconds, isTimeout } = useSocketTimer({
socket,
endsAt,
socketEvent: 'ping',
pingTime: 5000,
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.

SocketTimer에서 pingTime을 직접 주입하면 범용성이 없는것 같아 SocketTimer를 사용하는 곳에서 넘겨 받도록 했습니다.
현재는 대회 페이지에서 pingTime과 socketEvent를 상수화하고 SocketTimer에서 Props로 전달합니다.

});

useEffect(() => {
Expand Down
55 changes: 25 additions & 30 deletions frontend/src/hooks/timer/useSocketTimer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,47 +6,42 @@ 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();
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 Down