Created
December 16, 2015 21:55
-
-
Save 1995hnagamin/887fb505c4f356b76d1f to your computer and use it in GitHub Desktop.
P2P chat for plural persons with WebRTC
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
function add() { | |
var id = document.getElementById("id").value; | |
add_friend(id); | |
} | |
function add_friend(id, conn) { | |
if (typeof conn == "undefined") { | |
conn = peer.connect(id); | |
} | |
connections[id] = conn; | |
var myId = peer.id; | |
conn.on('data', function(data) { | |
if (data.ids.indexOf(myId) >= 0) { | |
return; | |
} | |
show_message(data.ids[0], data.message); | |
data.ids.push(myId); | |
submit_data(data); | |
look_for_friends(data); | |
}); | |
console.log("add: " + id); | |
} | |
function look_for_friends(data) { | |
data.ids.forEach(function(id) { | |
if (id in connections) { | |
return; | |
} | |
add_friend(id); | |
}); | |
} | |
function submit() { | |
var text = document.getElementById("message").value; | |
var data = { | |
ids: [peer.id], | |
message: text | |
}; | |
show_message(peer.id, text); | |
submit_data(data); | |
} | |
function show_message(id, message) { | |
document.getElementById("log").innerHTML += id + ": " + message + "<br>"; | |
} | |
var connections = {}; | |
var peer = null; | |
function submit_data(data) { | |
for (id in connections) { | |
if (data.ids.indexOf(id) >= 0) { | |
continue; | |
} | |
var conn = connections[id]; | |
conn.send(data); | |
console.log("submit: ", id); | |
console.log(data); | |
} | |
} | |
function initialize() { | |
peer = new Peer({key: 'consumer key'}); | |
peer.on('open', function(id) { | |
console.log(id); | |
}); | |
peer.on('connection', function(conn) { | |
add_friend(conn.peer, conn); | |
}); | |
} |
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 lang="ja"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>chat</title> | |
</head> | |
<body> | |
<input type="text" id="id"> | |
<input type="button" value="add" onclick="add();"> | |
<br> | |
<div id="log"></div> | |
<br> | |
<input type="text" id="message"> | |
<input type="button" value="submit" onclick="submit();"> | |
<script src="http://cdn.peerjs.com/0.3/peer.js"></script> | |
<script src="./app.js"></script> | |
<script>initialize();</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment