i have a project in react native that sends via websocket real-time coordinates via a node backend server and after im receiving them from a react frontend page. The problem i have is that when the app is in background the websocket wont work also location tracking. Any ideas?
Backend Code:
// Import the 'ws' (WebSocket) module
const WebSocket = require('ws');
// Create a new WebSocket server instance, listening on port 8080
const wss = new WebSocket.Server({ port: process.env.PORT || 8080 });
// Initialize an array to store coordinates
const coordinates = [];
// Event listener for when a client connects to the server
wss.on('connection', function connection(ws) {
console.log('A new client connected');
// Event listener for when a message is received from a client
ws.on('message', function incoming(message) {
console.log('Received: %s', message);
// Parse the incoming message (assuming it's JSON)
try {
const data = JSON.parse(message);
// Push the coordinates to the array
coordinates.push(data);
// Broadcast the message to all connected clients
wss.clients.forEach(function each(client) {
if (client !== ws && client.readyState === WebSocket.OPEN) {
// Send the message to all clients except the sender
client.send(JSON.stringify(data));
}
});
} catch (error) {
console.error('Error parsing message:', error);
}
});
// Event listener for when the connection is closed
ws.on('close', function close() {
console.log('Client disconnected');
});
console.log('WebSocket server listening on port 8080');
});
and React Native code:
const wsRef = useRef(null);
useEffect(() => {
// Establish WebSocket connection
wsRef.current = new WebSocket('wss://websocketa-52220f631af2.herokuapp.com/');
// Event handler for when WebSocket connection is open
wsRef.current.onopen = () => {
console.log('WebSocket connected');
};
// Event handler for when WebSocket receives a message
wsRef.current.onmessage = (event) => {
console.log('Received message:', event.data);
};
// Event handler for WebSocket errors
wsRef.current.onerror = (error) => {
console.error('WebSocket error:', error);
};
// Clean up WebSocket connection on component unmount
return () => {
wsRef.current.close();
};
}, []);
// Function to send location data to the server
const sendLocationToServer = (latitude, longitude) => {
if (wsRef.current) {
wsRef.current.send(JSON.stringify({ latitude, longitude }));
}
};
// Request permission to access location
const handleConnectButtonPress = () => {
// Run getCurrentPosition immediately
getCurrentPosition();
// Run getCurrentPosition every 5 seconds
setInterval(getCurrentPosition, 5000);
showLocationServiceNotification();
};
// Get the current position
const getCurrentPosition = () => {
Geolocation.getCurrentPosition(
position => {
const { latitude, longitude } = position.coords;
console.log('Latitude:', latitude);
console.log('Longitude:', longitude);
// Send location data to the server
sendLocationToServer(latitude, longitude);
},
error => {
console.log('Error getting location:', error);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
};
const showLocationServiceNotification = () => {
PushNotification.localNotification({
channelId: 'location-service-channel',
title: 'Location Service',
message: 'Location service is running in the background.',
});
};
// Request permission to access location
useEffect(() => {
Geolocation.requestAuthorization();
}, []);
and the manifest:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACTIVITY_RECOGNITION" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
I tried to install some libraries like react-native-geolocation but couldn’t find a solution..
New contributor
Ioannis Kaldellis is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.