-
-
Notifications
You must be signed in to change notification settings - Fork 33
Open
Description
Hey @kirillzyusko and team,
I am building an application where one user is the receiver and the other is the sender, even when there is no internet connection.
I have achieved this feature using react-native-tcp, but it requires too much manual intervention. To make it more automatic, I discovered this library.
However, I am now unsure if this library supports large base64 strings.
Currently, I can call the connect() function successfully, as it doesn't throw an error, indicating the devices are connected.
My next step is to send the actual base64 string to the receiver.
Here is my actual code:
import React, { useEffect, useState } from 'react';
import {
StyleSheet,
Text,
View,
Button,
PermissionsAndroid,
TouchableOpacity,
Alert,
} from 'react-native';
import WifiP2P, {
connect,
initialize,
receiveMessage,
sendMessage,
startDiscoveringPeers,
stopDiscoveringPeers,
subscribeOnPeersUpdates,
} from 'react-native-wifi-p2p';
import { check, request, PERMISSIONS, RESULTS } from 'react-native-permissions';
const P2P = () => {
const [peers, setPeers] = useState(null);
const [data, setData] = useState('');
const [connected, setConnected] = useState(false);
useEffect(() => {
checkPermission();
}, []);
const checkPermission = async () => {
try {
const locationPermission = await check(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
if (locationPermission === RESULTS.GRANTED) {
initializeWiFiDirect();
} else {
requestPermission();
}
} catch (error) {
console.error('Error checking permission:', error);
}
};
const requestPermission = async () => {
try {
const result = await request(PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION);
if (result === RESULTS.GRANTED) {
initializeWiFiDirect();
} else {
console.log('Location permission denied');
}
} catch (error) {
console.error('Error requesting permission:', error);
}
};
const initializeWiFiDirect = async () => {
try {
console.log('WiFi Direct initialized');
subscribeToPeersChanges();
} catch (error) {
console.error('Failed to initialize WiFi Direct:', error);
}
};
const subscribeToPeersChanges = () => {
const discoverPeersSubscription = subscribeOnPeersUpdates((deviceList) => {
setPeers(deviceList);
});
return () => {
discoverPeersSubscription.remove();
};
};
const discoverPeers = async () => {
try {
setPeers(null);
await startDiscoveringPeers();
} catch (error) {
console.error('Error discovering peers:', error);
}
};
const connectToPeer = async (deviceAddress) => {
try {
console.log(deviceAddress);
await connect(deviceAddress);
Alert.alert('Connected');
setConnected(true);
sendData(deviceAddress);
await stopDiscoveringPeers();
} catch (err) {
console.log(err);
}
};
const sendData = async (deviceAddress) => {
try {
await sendMessage(deviceAddress, 'anurag');
Alert.alert('Data Sent');
} catch (e) {
console.log(e);
}
};
const receiveData = async () => {
try {
console.log('receiveData');
receiveMessage()
.then((msg) => console.log('Message received successfully', msg))
.catch((err) => console.log('Error while receiving message', err));
Alert.alert('Data Received');
} catch (e) {
console.log(e);
}
};
return (
<View style={styles.container}>
<Text style={styles.title}>WiFi Direct Example</Text>
<Button title="Discover Peers" onPress={discoverPeers} />
<Text style={styles.subtitle}>Available Peers:</Text>
{peers?.devices.length > 0 &&
peers?.devices.map((peer) => (
<TouchableOpacity
style={{ backgroundColor: 'red', padding: 20 }}
key={peer.deviceAddress}
onPress={() => connectToPeer(peer.deviceAddress)}>
<Text style={{ color: 'white' }}>{peer.deviceName}</Text>
</TouchableOpacity>
))}
<Button title="Receive Data" onPress={receiveData} />
{data && <Text>{data}</Text>}
</View>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
padding: 20,
},
title: {
fontSize: 24,
fontWeight: 'bold',
marginBottom: 20,
}
})
Please take a look and let me know if any further adjustments are required.
Metadata
Metadata
Assignees
Labels
No labels