Last active
May 27, 2025 08:06
-
-
Save tsumarios/fd5a78aac246ad05d277a0ee4a7e84d0 to your computer and use it in GitHub Desktop.
Simple P2P chat example implemented via 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
| <!DOCTYPE html> | |
| <html> | |
| <head> | |
| <title>P2P Chat Example with PeerJS</title> | |
| <script src="https://cdn.jsdelivr.net/npm/peerjs@1.5.2/dist/peerjs.min.js"></script> | |
| </head> | |
| <body> | |
| <input id="peer-id" placeholder="Enter remote peer ID"> | |
| <button onclick="connect()">Connect</button><br> | |
| <textarea id="messages" readonly></textarea><br> | |
| <input id="message-input" placeholder="Message"> | |
| <button onclick="sendMessage()">Send</button> | |
| <script> | |
| const peer = new Peer(); // Use {host:'localhost', port:9000, path:'/chat'} for custom server | |
| let conn; | |
| peer.on('open', id => { | |
| console.log("My peer ID is: " + id); | |
| }); | |
| peer.on('connection', c => { | |
| conn = c; | |
| conn.on('data', data => { | |
| document.getElementById('messages').value += "Peer: " + data + "\n"; | |
| }); | |
| }); | |
| function connect() { | |
| const remoteId = document.getElementById('peer-id').value; | |
| conn = peer.connect(remoteId); | |
| conn.on('open', () => { | |
| conn.on('data', data => { | |
| document.getElementById('messages').value += "Peer: " + data + "\n"; | |
| }); | |
| }); | |
| } | |
| function sendMessage() { | |
| const msg = document.getElementById('message-input').value; | |
| conn.send(msg); | |
| document.getElementById('messages').value += "You: " + msg + "\n"; | |
| document.getElementById('message-input').value = ''; | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment