diff --git a/src/pages/GamePage/hooks/useWebsocket.ts b/src/pages/GamePage/hooks/useWebsocket.ts index f95424f5..81a430e1 100644 --- a/src/pages/GamePage/hooks/useWebsocket.ts +++ b/src/pages/GamePage/hooks/useWebsocket.ts @@ -1,5 +1,5 @@ import './init.ts'; -import { Client } from '@stomp/stompjs'; +import { Client, StompSubscription } from '@stomp/stompjs'; import { useEffect, useRef } from 'react'; import SockJS from 'sockjs-client'; import { BASE_PATH } from '@/generated/base'; @@ -11,6 +11,7 @@ import { PayloadType } from '../types/websocketType.ts'; const useWebsocket = (roomId: number | null) => { const stompClient = useRef(); + const ingameSubscription = useRef(); const connectHeaders = getToken(); @@ -117,12 +118,16 @@ const useWebsocket = (roomId: number | null) => { }; const onIngameConnected = () => { - stompClient.current?.subscribe( + ingameSubscription.current = stompClient.current?.subscribe( `/from/game/${roomId}`, (e) => onIngameMessageReceived(e), connectHeaders ); }; + const onIngameDisconnected = () => { + ingameSubscription.current?.unsubscribe(); + }; + const handleConnectIngame = (roomId: number) => { stompClient.current?.publish({ destination: `/to/game/${roomId}/connect`, @@ -138,6 +143,7 @@ const useWebsocket = (roomId: number | null) => { setIsIngameWsError(true); } if (responsePublish.type === 'FINISH') { + onIngameDisconnected(); setAllMembers(responsePublish.allMembers); } };