Created
May 31, 2023 19:42
-
-
Save iQuickDev/7d2e633fafb7526ffba9efdf7a52f953 to your computer and use it in GitHub Desktop.
Peer.js Simple Demo
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="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta http-equiv="X-UA-Compatible" content="IE=edge"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>Omegle Clone</title> | |
<style> | |
textarea { | |
width: 500px; | |
height: 300px; | |
} | |
</style> | |
</head> | |
<body> | |
<textarea id="messages" readonly></textarea> | |
<br> | |
<input id="text" type="text"> | |
<button id="send">Send</button> | |
<script src="https://unpkg.com/[email protected]/dist/peerjs.min.js"></script> | |
<script> | |
const params = new URLSearchParams(window.location.href.split('?')[1]) | |
const id = params.get('id') | |
const peer = new Peer() | |
const textarea = document.querySelector('#messages') | |
const sendBtn = document.querySelector('#send') | |
const text = document.querySelector('#text') | |
peer.on('open', (yourID) => | |
{ | |
console.log('ID: ' + yourID) | |
if (id) | |
{ | |
const connection = peer.connect(id) | |
connection.on('open', () => | |
{ | |
sendBtn.addEventListener('click', () => | |
{ | |
connection.send(text.value) | |
text.value = '' | |
}) | |
}) | |
connection.on('close', () => console.log('CONNECTION CLOSED BY PEER')) | |
connection.on('error', (e) => console.log('CONNECTION ERRORED ' + e)) | |
connection.on('data', (data) => | |
{ | |
textarea.value += data + '\n' | |
}) | |
} | |
}) | |
peer.on('connection', (connection) => | |
{ | |
connection.on('open', () => | |
{ | |
sendBtn.addEventListener('click', () => | |
{ | |
connection.send(text.value) | |
text.value = '' | |
}) | |
}) | |
connection.on('data', (data) => | |
{ | |
textarea.value += data + '\n' | |
}) | |
connection.on('close', () => console.log('CONNECTION CLOSED BY PEER')) | |
connection.on('error', (e) => console.log('CONNECTION ERRORED ' + e)) | |
}) | |
peer.on('error', (e) => | |
{ | |
console.log(e) | |
}) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment