Last active
November 28, 2019 22:31
-
-
Save strawstack/791f4ae49604bf5558dce276a9f619fc to your computer and use it in GitHub Desktop.
P2P Connection Establishment code for a blog article: http://regularmemory.blog/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!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