-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathApp.tsx
80 lines (63 loc) · 1.97 KB
/
App.tsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
import Peer, { DataConnection } from 'peerjs';
import React, { useEffect, useState } from 'react';
import { View, Text, TextInput, Button } from 'react-native';
const App = () => {
const peer = new Peer({
port: 443,
path: '/',
});
const [peerId, setPeerId] = useState('');
const [peerConnection, setPeerConnection] = useState<DataConnection | null>(null);
useEffect(() => {
// Listen for incoming connections
peer.on('connection', (connection) => {
console.log('Received connection');
setPeerConnection(connection);
connection.on('data', (data) => {
console.log('Received data:', data);
});
connection.on('close', () => {
console.log('Connection closed');
setPeerConnection(null);
});
});
}, []);
const connectToPeer = () => {
const connection = peer.connect(peerId);
connection.on('open', () => {
console.log('Connection established');
setPeerConnection(connection);
});
connection.on('data', (data) => {
console.log('Received data:', data);
});
connection.on('close', () => {
console.log('Connection closed');
setPeerConnection(null);
});
};
const sendData = () => {
if (peerConnection) {
peerConnection.send('Hello from PeerJS!');
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Text style={{ fontSize: 24, marginBottom: 20 }}>PeerJS Demo</Text>
<TextInput
style={{ height: 40, width: 200, borderColor: 'gray', borderWidth: 1, marginBottom: 20 }}
placeholder="Enter peer ID"
onChangeText={(text) => setPeerId(text)}
value={peerId}
/>
<Button title="Connect" onPress={connectToPeer} />
{peerConnection && (
<>
<Text style={{ marginTop: 20 }}>Connected to peer {peerId}</Text>
<Button title="Send data" onPress={sendData} />
</>
)}
</View>
);
};
export default App;