internet
Version:
Framework for creating peer-to-peer browser networks
50 lines (42 loc) • 1.67 kB
HTML
<title>Ping</title>
<script>P_DEBUGGING_ENABLED = false;</script>
<script src="/p.js"></script>
<script>
var p = P.create();
var onrampServerAddress = 'ws://' + location.hostname + ':20500/';
// Establish a connection to an onramp server. The onramp
// server speaks the 'p' protocol and will allow us to make
// connections to peers.
console.log('connecting to onramp server at ' + onrampServerAddress);
var onramp = p.connect(onrampServerAddress);
// Whenever another peer connects to the onramp server (or
// if there are already peers connected to it), it will send
// a message with an address for the peer. We can then ask the
// onramp server to connect to the peer at the address.
onramp.on('message', function(peerAddress){
// Using the onramp connection as a signaling channel,
// connect to peer addresss.
console.log('connecting to peer at ' + peerAddress);
var peer = onramp.connect({ address: peerAddress, offerData: "Hi!" });
// When the connection opens, send an initial ping
// to start the dialog
peer.on('open', function(){
console.log('connected to peer at ' + peerAddress);
peer.send('ping?');
console.log(peerAddress, ' <-- ping?');
});
// Whenever we receive a response from the peer,
// wait one second and respond with another ping.
peer.on('message', function(message){
console.log(peerAddress, ' --> ' + message);
setTimeout(function(){
peer.send('ping?');
console.log(peerAddress, ' <-- ping?');
}, 3000);
});
});
// Get notifications of closed connections
p.on('disconnection', function(peer){
console.log(peer.address, ' disconnected');
});
</script>