Created
April 12, 2014 09:08
-
-
Save piatra/10526052 to your computer and use it in GitHub Desktop.
peer js demo
This file contains hidden or 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> | |
<title></title> | |
</head> | |
<body> | |
<button>connect</button> | |
<script src="http://cdn.peerjs.com/0.3/peer.js"></script> | |
<script type="text/javascript"> | |
var peer = new Peer({key: 'im289css0byphkt9'}); | |
var myid; | |
peer.on('open', function(id) { | |
myid = id; | |
appendMsg('My peer ID is: <strong>' + id + '</strong>'); | |
appendMsg('Open a new tab and use this to connect'); | |
}); | |
var button = document.querySelector('button'); | |
button.addEventListener('click', function() { | |
var peerID = prompt('Peer id?'); | |
if (!peerID) { | |
appendMsg('No peer id added. Try again'); | |
return; | |
} | |
if (myid == peerID) { | |
appendMsg('You can\'t connect to yourself. Try again in a new tab'); | |
return; | |
} | |
var conn = peer.connect(peerID); // who to connect to | |
conn.on('open', function(){ // when the connection is ready | |
appendMsg('Connection opened. Sent message'); | |
appendMsg('Try looking in the other tab'); | |
conn.send('hi!'); | |
}); | |
}, false); | |
peer.on('connection', function(conn) { | |
appendMsg('Connected to remote peer'); | |
// this event is triggered when a connection | |
// has been established with a remote peer | |
// we can use the `conn` object to listen for data events | |
conn.on('open', function() { | |
conn.on('data', function(data) { | |
// data contains the received message | |
console.log(data); | |
appendMsg('Message from peer: ' + data); | |
}); | |
}); | |
}); | |
function appendMsg(msg) { | |
var el = document.createElement('p'); | |
el.innerHTML = msg; | |
document.body.appendChild(el); | |
} | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment