|
| 1 | +[](https://gitpod.io/#https://github.com/ambianic/peerjs-python) |
| 2 | + |
1 | 3 | # peerjs-python |
2 | 4 |
|
3 | 5 | Python port of [PeerJS](https://github.com/peers) client. |
@@ -60,6 +62,55 @@ Initial working prototype completed. PeerJS Python is now able to connect over W |
60 | 62 | - [ ] >90% code coverage with CI tests. |
61 | 63 | - [ ] Port media support. |
62 | 64 |
|
| 65 | +## Code Examples |
| 66 | + |
| 67 | +A typical p2p session takes these steps: |
| 68 | +1. Establish signaling server session that enables peers to discover each other. |
| 69 | +2. Discover remote peer ID (either via signaling server room affinity or other means) |
| 70 | +3. Request connection to remote peer via signaling server |
| 71 | +4. Connect to remote peer via WebRTC ICE protocol. |
| 72 | +5. Exchange data or media with remote peer over p2p WebRTC connection. |
| 73 | + |
| 74 | +The following code snippet shows the initial part of establishing a signaling server connection. |
| 75 | + |
| 76 | +``` |
| 77 | + options = PeerOptions( |
| 78 | + host=config['host'], |
| 79 | + port=config['port'], |
| 80 | + secure=config['secure'], |
| 81 | + token=new_token, |
| 82 | + config=RTCConfiguration( |
| 83 | + iceServers=[RTCIceServer(**srv) for srv in config['ice_servers']] |
| 84 | + ) |
| 85 | + ) |
| 86 | + peer = Peer(id=savedPeerId, peer_options=options) |
| 87 | + await peer.start() |
| 88 | + log.info('peer activated') |
| 89 | + _setPnPServiceConnectionHandlers(peer) |
| 90 | +``` |
| 91 | + |
| 92 | +Once a signaling server connection is established, a peer can request connection to another peer or listen for requests from a remote peer. |
| 93 | +The example snippet bellow shows the latter: |
| 94 | + |
| 95 | +``` |
| 96 | + @peer.on(PeerEventType.Connection) |
| 97 | + async def peer_connection(peerConnection): |
| 98 | + log.info('Remote peer trying to establish connection') |
| 99 | + _setPeerConnectionHandlers(peerConnection) |
| 100 | +``` |
| 101 | + |
| 102 | +After a p2p connection is established, a peer can receive and send application messages. The following snippet shows how a peer receives a message: |
| 103 | + |
| 104 | +``` |
| 105 | + @peerConnection.on(ConnectionEventType.Data) |
| 106 | + async def pc_data(data): |
| 107 | + log.debug('data received from remote peer \n%r', data) |
| 108 | +``` |
| 109 | + |
| 110 | +For a complete working example see [this file](https://github.com/ambianic/peerjs-python/blob/master/src/peerjs/ext/http-proxy.py). |
| 111 | + |
| 112 | + |
| 113 | + |
63 | 114 | ## Other Related Open Source projects |
64 | 115 |
|
65 | 116 | There are several great projects that solve the problem of accessing IoT devices behind firewall via tunneling servers. |
|
0 commit comments