|
| 1 | +# React Native PeerJS |
| 2 | + |
| 3 | +[react-native-webrtc](https://github.com/react-native-webrtc/react-native-webrtc) has brought WebRTC to React Native. [PeerJS](https://github.com/peers/peerjs) is a simple API to work with WebRTC in the Browser. |
| 4 | + |
| 5 | +I made it so that PeerJS works with react-native-webrtc in a React Native application. |
| 6 | + |
| 7 | +## Install |
| 8 | + |
| 9 | +Install react-native-webrtc according to their install guide. Then add react-native-peerjs: |
| 10 | + |
| 11 | +``` |
| 12 | +yarn add react-native-peerjs |
| 13 | +``` |
| 14 | + |
| 15 | +## Usage |
| 16 | + |
| 17 | +Just refer to the PeerJS documentation. Here is an example: |
| 18 | + |
| 19 | +```js |
| 20 | +import Peer from 'react-native-peerjs'; |
| 21 | + |
| 22 | +const localPeer = new Peer(); |
| 23 | +localPeer.on('error', console.log); |
| 24 | + |
| 25 | +localPeer.on('open', localPeerId => { |
| 26 | + console.log('Local peer open with ID', localPeerId); |
| 27 | + |
| 28 | + const remotePeer = new Peer(); |
| 29 | + remotePeer.on('error', console.log); |
| 30 | + remotePeer.on('open', remotePeerId => { |
| 31 | + console.log('Remote peer open with ID', remotePeerId); |
| 32 | + |
| 33 | + const conn = remotePeer.connect(localPeerId); |
| 34 | + conn.on('error', console.log); |
| 35 | + conn.on('open', () => { |
| 36 | + console.log('Remote peer has opened connection.'); |
| 37 | + console.log('conn', conn); |
| 38 | + conn.on('data', data => console.log('Received from local peer', data)); |
| 39 | + console.log('Remote peer sending data.'); |
| 40 | + conn.send('Hello, this is the REMOTE peer!'); |
| 41 | + }); |
| 42 | + }); |
| 43 | +}); |
| 44 | + |
| 45 | +localPeer.on('connection', conn => { |
| 46 | + console.log('Local peer has received connection.'); |
| 47 | + conn.on('error', console.log); |
| 48 | + conn.on('open', () => { |
| 49 | + console.log('Local peer has opened connection.'); |
| 50 | + console.log('conn', conn); |
| 51 | + conn.on('data', data => console.log('Received from remote peer', data)); |
| 52 | + console.log('Local peer sending data.'); |
| 53 | + conn.send('Hello, this is the LOCAL peer!'); |
| 54 | + }); |
| 55 | +}); |
| 56 | +``` |
| 57 | + |
0 commit comments