Skip to content

Commit f6eec5f

Browse files
committed
[FE] feat; useStompWebRTC hook 추가 (#74)
1 parent ee80e43 commit f6eec5f

File tree

1 file changed

+69
-0
lines changed

1 file changed

+69
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
import { Client, Frame } from '@stomp/stompjs';
2+
import { useEffect, useRef, useState } from 'react';
3+
4+
interface UseStompWebRTCProps {
5+
roomId: string;
6+
}
7+
8+
const useStompWebRTC = ({ roomId }: UseStompWebRTCProps) => {
9+
const [isConnected, setIsConnected] = useState(false);
10+
const clientRef = useRef<Client | null>(null);
11+
12+
const SERVER_URL = import.meta.env.VITE_SIGNALING;
13+
14+
useEffect(() => {
15+
const token = localStorage.getItem('access_token');
16+
let socketToken: string;
17+
if (token) socketToken = token;
18+
19+
const client = new Client({
20+
webSocketFactory: () => new WebSocket(SERVER_URL, ['v10.stomp', socketToken]),
21+
connectHeaders: { Authorization: `Bearer ${token}` },
22+
// debug: (msg) => console.log('STOMP DEBUG:', msg),
23+
reconnectDelay: 5000,
24+
heartbeatIncoming: 10000,
25+
heartbeatOutgoing: 10000,
26+
27+
onConnect: (frame: Frame) => {
28+
console.log('✅ STOMP 연결 성공!', frame);
29+
30+
// 연결 성공 시 subscribe
31+
client.subscribe(`/topic/users/${roomId}`, (message) => {
32+
console.log('📩 users 받은 메시지:', message);
33+
});
34+
35+
client.subscribe(`/topic/answer/${roomId}`, (message) => {
36+
console.log('📩 answer 받은 메시지:', message);
37+
});
38+
39+
client.subscribe(`/topic/candidate/${roomId}`, (message) => {
40+
console.log('📩 candidate 받은 메시지:', message);
41+
});
42+
43+
setIsConnected(true);
44+
},
45+
46+
onWebSocketError: (error: Error) => {
47+
console.log('WebSocket 에러', error);
48+
},
49+
50+
onStompError: (frame) => {
51+
console.error('❌ STOMP 오류 발생!', frame);
52+
},
53+
});
54+
55+
client.activate();
56+
clientRef.current = client;
57+
58+
return () => {
59+
client.deactivate();
60+
clientRef.current = null;
61+
setIsConnected(false);
62+
console.log('✅ WebSocket 연결 해제됨');
63+
};
64+
}, [roomId]);
65+
66+
return { client: clientRef.current, isConnected };
67+
};
68+
69+
export default useStompWebRTC;

0 commit comments

Comments
 (0)