Created
January 14, 2014 23:33
-
-
Save jchris/8428070 to your computer and use it in GitHub Desktop.
Hello world with PeerJS
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
<html> | |
<head> | |
<title>PeerJS Hello</title> | |
</head> | |
<body> | |
<p> | |
Your peer id is: <span id="peerid"></span> | |
</p> | |
<form id="connect"> | |
Connect to: <input type="text"/> | |
<input type="submit"/> | |
</form> | |
<div id="chat"> | |
You are connected to: <span id="remoteid"></span> | |
<form > | |
Send message: <input type="text"/> | |
<submit/> | |
</form> | |
<ul id="messages"></ul> | |
</div> | |
</body> | |
<script src="http://cdn.peerjs.com/0.3/peer.js"></script> | |
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> | |
<script type="text/javascript"> | |
var peer = new Peer({host: 'localhost', port: 9000}) | |
peer.on("open", function(id){ | |
$("#chat").hide() | |
$("#peerid").text(id) | |
$("form#connect").submit(function(){ | |
var remoteID = $(this).find('input[type="text"]').val() | |
console.log("connect to", remoteID); | |
var conn = peer.connect(remoteID) | |
gotConnection(conn) | |
return false; | |
}) | |
}) | |
peer.on("connection", gotConnection) | |
function gotConnection(conn) { | |
conn.on("error", function(err){ | |
console.error("connection error", err, conn) | |
}) | |
conn.on("open", function(){ | |
console.log("conn open", conn) | |
$("#remoteid").text(conn.peer) | |
$("form#connect").hide() | |
$("#chat").show() | |
$("#chat form").submit(function(){ | |
var message = $(this).find('input[type="text"]').val() | |
console.log("send", message); | |
conn.send(message) | |
$(this).find('input[type="text"]').val("") | |
$("#messages").append($('<li>'+peer.id+': '+message+'</li>')) | |
return false; | |
}) | |
conn.on("data", function(data) { | |
console.log("got", data); | |
$("#messages").append($('<li>'+conn.peer+': '+data+'</li>')) | |
}) | |
}) | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment