Гость
Проблема с множественным соединением с сокетом io в ответном нативном использовании @supersami/rn-foreground-service
Сообщение
Гость » 09 апр 2024, 10:40
Я отслеживаю местоположение пользователя с помощью @supersami/rn-foreground-service в React Native
Я столкнулся с проблемой сокета, каждый пользователь подключался несколько раз к одному устройству
Код: Выделить всё
useEffect(() => {
socket.current = io(`${mainDomain}/driverLocation`, {
transports: ['websocket']
});
socket.current.on('connect', () => {
console.log('Connected to the Socket.io server');
});
const info = getDeviceInfo();
setDeviceInfo(info);
return () => {
socket.current.disconnect();
}
}, []);
useEffect(() => {
if (permissionGranted && user?.location_tracking == 1) {
requestForBatteryOptmine();
startTask();
} else {
stopTask();
}
}, [permissionGranted])
const startTask = () => {
ReactNativeForegroundService.add_task(() => getLocation(), {
delay: 5000,
onLoop: true,
taskId: 'taskid',
onError: e => console.log('Error logging:', e),
});
ReactNativeForegroundService.start({
id: 1244,
title: 'Location service',
message: 'Your app is running.',
icon: 'ic_launcher',
setOnlyAlertOnce: true,
color: '#000000',
importance: 'high',
ongoing: true,
persist: true,
});
};
const emitLocationUpdateThrottled = throttle((socketIo, userId, latitude, longitude, time, phone) => {
socketIo.emit('locationUpdate', { userId, latitude, longitude, time, phone });
}, 1000); // Emit at most every 1000ms (1 second)
const getLocation = async () => {
let isConnection = true;
NetInfo.addEventListener(state => {
isConnection = state.isConnected;
});
console.log("🚀 ~ file: Home.js:181 ~ getLocation ~ isConnection:", isConnection)
console.log("🚀 ~ file: home.js:111 ~ HomeScreen ~ getLocation ~ getLocation:", socket.current.connected,)
if (!(socket.current?.connected)) {
socket.current?.disconnect();
socket.current = io(`${mainDomain}/driverLocation`, {
transports: ['websocket']
});
socket.current.on('connect', () => {
console.log('Connected to the Socket.io server');
});
}
const watchId = Geolocation.watchPosition(
async (position) => {
const { latitude, longitude } = position.coords;
let newLocationData = { userId: user.id, latitude: latitude, longitude: longitude, time: getCurrentTimeAndDate(), phone: user.mobile_no, isSync: 1 }
emitLocationUpdateThrottled(socket.current, user.id, latitude, longitude, getCurrentTimeAndDate(), user.mobile_no);
if (isConnection == false) {
const storedLocationData = await AsyncStorage.getItem('offline_locaiton_data');
if (storedLocationData) {
const parsedStoredData = JSON.parse(storedLocationData);
const updatedData = [...parsedStoredData, newLocationData];
await AsyncStorage.setItem('offline_locaiton_data', JSON.stringify(updatedData));
} else {
const updatedData = [newLocationData];
await AsyncStorage.setItem('offline_locaiton_data', JSON.stringify(updatedData));
}
}
},
(error) => {
console.log("🚀 ~ file: locationPermission.js:50 ~ watchLocation ~ error:", error)
},
{
enableHighAccuracy: true, // Use GPS if available
distanceFilter: 50, // Minimum distance (in meters) between location updates
timeout: 30000, // Maximum time (in milliseconds) to wait for a location update
maximumAge: 60000, // M
}
);
if (isConnection) {
const storedLocationData = await AsyncStorage.getItem('offline_locaiton_data');
if (storedLocationData && socket.current.connected) {
const offLocation = JSON.parse(storedLocationData);
console.log("🚀 ~ file: Home.js:286 ~ getLocation ~ offLocation:", offLocation)
offLocation.length > 0 && offLocation.map((loc) => {
console.log("🚀 ~ file: loc:", loc)
socket.current.emit('locationUpdate', loc)
})
setTimeout(() => {
AsyncStorage.removeItem('offline_locaiton_data')
}, 3000)
}
}
if (watchId) {
setTimeout(() => {
Geolocation.clearWatch(watchId);
}, 4000)
}
}
Я использую этот код для отслеживания местоположения пользователя, который подключался несколько раз и выдавал тысячи повторяющихся местоположений с одинаковым временем и датой.
проблемы1 несколько подключений.
2 одно местоположение выдает несколько раз при каждом подключении
3 высокая нагрузка на выходную сеть сервера.
Подробнее здесь:
https://stackoverflow.com/questions/782 ... rsami-rn-f
1712648456
Гость
Я отслеживаю местоположение пользователя с помощью @supersami/rn-foreground-service в React Native Я столкнулся с проблемой сокета, каждый пользователь подключался несколько раз к одному устройству [code]useEffect(() => { socket.current = io(`${mainDomain}/driverLocation`, { transports: ['websocket'] }); socket.current.on('connect', () => { console.log('Connected to the Socket.io server'); }); const info = getDeviceInfo(); setDeviceInfo(info); return () => { socket.current.disconnect(); } }, []); useEffect(() => { if (permissionGranted && user?.location_tracking == 1) { requestForBatteryOptmine(); startTask(); } else { stopTask(); } }, [permissionGranted]) const startTask = () => { ReactNativeForegroundService.add_task(() => getLocation(), { delay: 5000, onLoop: true, taskId: 'taskid', onError: e => console.log('Error logging:', e), }); ReactNativeForegroundService.start({ id: 1244, title: 'Location service', message: 'Your app is running.', icon: 'ic_launcher', setOnlyAlertOnce: true, color: '#000000', importance: 'high', ongoing: true, persist: true, }); }; const emitLocationUpdateThrottled = throttle((socketIo, userId, latitude, longitude, time, phone) => { socketIo.emit('locationUpdate', { userId, latitude, longitude, time, phone }); }, 1000); // Emit at most every 1000ms (1 second) const getLocation = async () => { let isConnection = true; NetInfo.addEventListener(state => { isConnection = state.isConnected; }); console.log("🚀 ~ file: Home.js:181 ~ getLocation ~ isConnection:", isConnection) console.log("🚀 ~ file: home.js:111 ~ HomeScreen ~ getLocation ~ getLocation:", socket.current.connected,) if (!(socket.current?.connected)) { socket.current?.disconnect(); socket.current = io(`${mainDomain}/driverLocation`, { transports: ['websocket'] }); socket.current.on('connect', () => { console.log('Connected to the Socket.io server'); }); } const watchId = Geolocation.watchPosition( async (position) => { const { latitude, longitude } = position.coords; let newLocationData = { userId: user.id, latitude: latitude, longitude: longitude, time: getCurrentTimeAndDate(), phone: user.mobile_no, isSync: 1 } emitLocationUpdateThrottled(socket.current, user.id, latitude, longitude, getCurrentTimeAndDate(), user.mobile_no); if (isConnection == false) { const storedLocationData = await AsyncStorage.getItem('offline_locaiton_data'); if (storedLocationData) { const parsedStoredData = JSON.parse(storedLocationData); const updatedData = [...parsedStoredData, newLocationData]; await AsyncStorage.setItem('offline_locaiton_data', JSON.stringify(updatedData)); } else { const updatedData = [newLocationData]; await AsyncStorage.setItem('offline_locaiton_data', JSON.stringify(updatedData)); } } }, (error) => { console.log("🚀 ~ file: locationPermission.js:50 ~ watchLocation ~ error:", error) }, { enableHighAccuracy: true, // Use GPS if available distanceFilter: 50, // Minimum distance (in meters) between location updates timeout: 30000, // Maximum time (in milliseconds) to wait for a location update maximumAge: 60000, // M } ); if (isConnection) { const storedLocationData = await AsyncStorage.getItem('offline_locaiton_data'); if (storedLocationData && socket.current.connected) { const offLocation = JSON.parse(storedLocationData); console.log("🚀 ~ file: Home.js:286 ~ getLocation ~ offLocation:", offLocation) offLocation.length > 0 && offLocation.map((loc) => { console.log("🚀 ~ file: loc:", loc) socket.current.emit('locationUpdate', loc) }) setTimeout(() => { AsyncStorage.removeItem('offline_locaiton_data') }, 3000) } } if (watchId) { setTimeout(() => { Geolocation.clearWatch(watchId); }, 4000) } } [/code] Я использую этот код для отслеживания местоположения пользователя, который подключался несколько раз и выдавал тысячи повторяющихся местоположений с одинаковым временем и датой. проблемы1 несколько подключений. 2 одно местоположение выдает несколько раз при каждом подключении 3 высокая нагрузка на выходную сеть сервера. Подробнее здесь: [url]https://stackoverflow.com/questions/78296827/multiple-connection-problem-with-socket-io-in-react-native-using-supersami-rn-f[/url]