signalrProvider.tsx 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. 'use client';
  2. import { createContext, useContext, useEffect, useState, useRef } from 'react';
  3. import * as signalR from '@microsoft/signalr';
  4. import { fetchLogout } from '@/lib/api/auth';
  5. const SignalRContext = createContext<{
  6. cryptoConnection: signalR.HubConnection | null;
  7. chatConnection: signalR.HubConnection | null;
  8. cryptoConnected: boolean;
  9. chatConnected: boolean;
  10. stopConnections: () => Promise<void>;
  11. reconnectChat: (accessToken?: string | null) => Promise<void>;
  12. }>({
  13. cryptoConnection: null,
  14. chatConnection: null,
  15. cryptoConnected: false,
  16. chatConnected: false,
  17. stopConnections: async () => {},
  18. reconnectChat: async () => {}
  19. });
  20. type Props = {
  21. children: React.ReactNode;
  22. accessToken: string|null;
  23. signalRCryptoUrl: string;
  24. signalRChatUrl: string;
  25. }
  26. export function SignalRProvider({ children, accessToken, signalRCryptoUrl, signalRChatUrl }: Props) {
  27. const cryptoConnectionRef = useRef<signalR.HubConnection|null>(null);
  28. const chatConnectionRef = useRef<signalR.HubConnection|null>(null);
  29. const [cryptoConnected, setCryptoConnected] = useState<boolean>(false);
  30. const [chatConnected, setChatConnected] = useState<boolean>(false);
  31. // 초기 렌더 시에만 전달됨. 토큰 갱신 시에는 reconnectChat()을 통해 수동으로 재연결 처리
  32. useEffect(() => {
  33. initCryptoConnection();
  34. initChatConnection(accessToken);
  35. return () => {
  36. stopConnections();
  37. };
  38. }, []);
  39. useEffect(() => {
  40. if (cryptoConnected) {
  41. console.info('SignalR Crypto Connected');
  42. }
  43. }, [cryptoConnected]);
  44. useEffect(() => {
  45. if (chatConnected) {
  46. console.info('SignalR Chat Connected');
  47. }
  48. }, [chatConnected]);
  49. const initCryptoConnection = async () => {
  50. try {
  51. if (cryptoConnectionRef.current && cryptoConnectionRef.current.state !== signalR.HubConnectionState.Disconnected) {
  52. return;
  53. }
  54. const conn = new signalR.HubConnectionBuilder().withUrl(signalRCryptoUrl).withAutomaticReconnect().build();
  55. await conn.start();
  56. setCryptoConnected(true);
  57. cryptoConnectionRef.current = conn;
  58. } catch (error) {
  59. console.error('SignalR Crypto Connect Failed:', error);
  60. }
  61. };
  62. const initChatConnection = async (accessToken?: string|null) => {
  63. try {
  64. if (chatConnectionRef.current && chatConnectionRef.current.state !== signalR.HubConnectionState.Disconnected) {
  65. await chatConnectionRef.current.stop();
  66. }
  67. const connectionOptions = accessToken ? { accessTokenFactory: async () => accessToken, withCredentials: true } : {};
  68. const conn = new signalR.HubConnectionBuilder().withUrl(signalRChatUrl, connectionOptions).withAutomaticReconnect().build();
  69. await conn.start();
  70. setChatConnected(true);
  71. conn.on('Connected', (message) => {
  72. console.info(message);
  73. });
  74. conn.on('Logout', (message) => {
  75. console.info(message);
  76. });
  77. conn.on('Kick', async () => {
  78. await fetchLogout();
  79. alert('관리자에 의해 강제 종료되었습니다.');
  80. localStorage.setItem('rememberMe', 'false');
  81. localStorage.removeItem('member');
  82. location.replace('/');
  83. });
  84. chatConnectionRef.current = conn;
  85. } catch (error) {
  86. console.error('SignalR Chat Connect Failed:', error);
  87. }
  88. };
  89. const stopConnections = async () => {
  90. if (chatConnectionRef.current && chatConnectionRef.current.state === signalR.HubConnectionState.Connected) {
  91. try {
  92. await chatConnectionRef.current.invoke('Logout');
  93. setChatConnected(false);
  94. } catch (error) {
  95. console.error('SignalR Chat Disconnect Failed:', error);
  96. }
  97. }
  98. if (cryptoConnectionRef.current && cryptoConnectionRef.current.state === signalR.HubConnectionState.Connected) {
  99. try {
  100. await cryptoConnectionRef.current.stop();
  101. setCryptoConnected(false);
  102. } catch (error) {
  103. console.error('SignalR Crypto Disconnect Failed:', error);
  104. }
  105. }
  106. };
  107. const reconnectChat = async (token?: string | null) => {
  108. await initChatConnection(token);
  109. };
  110. return (
  111. <SignalRContext.Provider value={{
  112. cryptoConnection: cryptoConnectionRef.current,
  113. chatConnection: chatConnectionRef.current,
  114. cryptoConnected,
  115. chatConnected,
  116. stopConnections,
  117. reconnectChat
  118. }}>
  119. {children}
  120. </SignalRContext.Provider>
  121. )
  122. }
  123. export function useSignalRContext() {
  124. return useContext(SignalRContext);
  125. }