728x90
반응형
import {Stomp} from '@stomp/stompjs';
import {useCallback, useEffect} from 'react';
import SockJS from 'sockjs-client';
import {stompClient} from '../../App';
import Config from '../config';
import showSlice from '../reudx/slices/show';
import {useAppDispatch} from '../reudx/store';
import NetInfo, {useNetInfo} from '@react-native-community/netinfo';

export const useSocket = () => {
console.log('::::::: useSocket render ::::::::');

const dispatch = useAppDispatch();

const initSocket = useCallback(() => {
console.log('::::::: init socket ::::::::');
stompClient.current = Stomp.over(function () {
return new SockJS(Config.SOCKET_URL);
});
// stompClient.client.appendMissingNULLonIncoming = true;
// stompClient.client.forceBinaryWSFrames = true;
}, []);

const disconnectHandler = useCallback(() => {
console.log('::::::: disconnectHandler :::::::');
stompClient.current.disconnect();
}, []);

const connectHandler = useCallback(() => {
console.log('::::::: connectHandler :::::::');
stompClient.current.connect(
{},
() => {
//connect
console.log('open');
dispatch(showSlice.actions.setSocketConnected(true));
},
() => {
//error
console.log('error');
dispatch(showSlice.actions.setSocketConnected(false));
},
() => {
//close
console.log('close');
dispatch(showSlice.actions.setSocketConnected(false));
},
);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

useEffect(() => {
let beforeState: boolean | null = true;
const unsubscribe = NetInfo.addEventListener(state => {
console.log(' ::::::::::::::::::::::::::::: ');
console.log('Connection type', state.type);
console.log('Is connected?', state.isConnected);
// dispatch(showSlice.actions.setIpAddress(state?.details?.ipAddress));

if (beforeState !== state.isConnected) {
console.log(
'network changed ::::::::::::::::::::: to ' + state.isConnected,
);

// todo 네트워크 재연결 뒤에 소켓 연결할지
// if (state.isConnected) {
// initSocket();
// connectHandler();
// }
}
beforeState = state.isConnected;
});

// Unsubscribe
return () => unsubscribe();
}, []);

useEffect(() => {
let beforeState:
| SockJS.CONNECTING
| SockJS.OPEN
| SockJS.CLOSING
| SockJS.CLOSED;

let timer = setInterval(() => {
// console.log('stompClient.current.state :::' + stompClient.current.state);
if (beforeState !== stompClient.current.state) {
console.log('changed :::::::::' + stompClient.current.state);
if (
stompClient.current.state === SockJS.OPEN ||
stompClient.current.state === SockJS.CONNECTING
) {
console.log('socket Connected::: true');
// dispatch(showSlice.actions.setSocketConnected(true));
} else {
console.log('socket Connected::: false');
// dispatch(showSlice.actions.setSocketConnected(false));
connectHandler();
}
}
beforeState = stompClient.current.state;
}, 1000);

return () => clearInterval(timer);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);

return {connectHandler, disconnectHandler, initSocket};
};

 

initSocket()

connectHandler()

로 필요한곳에서 사용하면 된다.

728x90
반응형

+ Recent posts