P2P Connection Establishment code for a blog article: http://regularmemory.blog/
<!DOCTYPE html> | |
<html><head> | |
<meta charset="utf-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1"> | |
<!-- Include the P2P library --> | |
<script src="https://unpkg.com/peerjs@1.0.0/dist/peerjs.min.js"></script> | |
<style> | |
html, body { | |
padding: 30px; | |
margin: 0px; | |
font-size: 1.2em; | |
} | |
</style> | |
</head> | |
<body> | |
<h1>P2P Connection Establishment Example</h1> | |
<p>Open the web inspector, and click the Console tab to see results.</p> | |
<!-- Use PeerJS API --> | |
<script> | |
// 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 | |
console.log(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) | |
conn.send(msg); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment