Skip to content

Instantly share code, notes, and snippets.



Last active Nov 28, 2019
What would you like to do?
P2P Connection Establishment code for a blog article:
<!DOCTYPE html>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Include the P2P library -->
<script src=""></script>
html, body {
padding: 30px;
margin: 0px;
font-size: 1.2em;
<h1>P2P Connection Establishment Example</h1>
<p>Open the web inspector, and click the Console tab to see results.</p>
<!-- Use PeerJS API -->
// Create a Peer
var peer = new Peer();
// Print PeerID to the Console
let peer_id;
peer.on('open', function(id) {
peer_id = id;
console.log('Your peer ID: ' + id);
// Listen for an incoming connection
peer.on('connection', function(conn) {
conn.on('data', function(data) {
// Log received data
// Connect to a peer
var conn;
function connect(peerID) {
conn = peer.connect(peerID);
// 'open' is called on successful connection to PeerServer
conn.on('open', function() {
// Send a hello message to a peer
conn.send(peer_id + " has connected with you");
// Inform client of connection
console.log("You have connected with: " + peerID);
// Send a message to a Peer you have connected with
function send(msg) {
if (conn != undefined)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment