PeerJS: PeerJS wraps the browser’s WebRTC implementation to provide a complete, configurable, and easy-to-use peer-to-peer connection API. Equipped with nothing but an ID, a peer can create a P2P data or media stream connection to a remote peer.
The code is pretty straight forward, and I’ve added comments to explain what each line does. Copy the code below into an
index.html file or download the code here.
In summary, the code above will print
your PeerID to the console. One can then call
connect(PeerID), where PeerID is someone else’s PeerID, to connect with a peer. Once the connection is established, call
msg(msg_text) to send a message to a peer, where
msg_text is a string representing the message you want to send.
Here I show screenshots where I have opened the console in the web inspector for two different tabs on the same machine. Note, this will also work between any two machines that are able to establish a P2P connection, which might exclude cell phones, some older browsers, and machines behind firewalls, but a P2P connection will work in a lot of cases!
If you want to see P2P in-action checkout an interactive Go board I built. Players can connect with P2P to sync board and menu state between clients.