I am trying to create a PeerJS connection where the host creates a connection by getting a generated Peer ID by calling peer.generateID()
. The host should then get this ID on screen and share with his/her client to connect and record some information in the localStorage. However no Peer ID is generated for connection and no message displayed as shown below:
<html>
<head>
<title>Peer to Peer Activity</title>
<script src="https://cdn.peerjs.io/latest/peerjs.min.js"></script>
</head>
<body>
<h1>Peer to Peer Activity</h1>
<p>Select an option:</p>
<button onclick="createHost()">Create Host</button>
<button onclick="joinHost()">Join Host</button>
<input type="text" id="messageInput" />
<button onclick="sendMessage()">Send Message</button>
<div id="message"></div>
<script>
// Create a PeerJS object
var peer = new PeerJS();
// Create a data channel
var dataChannel = peer.createDataChannel('my-channel');
// Listen for incoming messages
dataChannel.onmessage = function(event) {
// Update the message on the screen
document.getElementById('message').innerHTML = event.data;
// Save the message to local storage
localStorage.setItem('message', event.data);
};
// Create a host
function createHost() {
// Generate a peer ID
var peerID = peer.generateID();
// Create a new host session
var session = peer.createSession({
id: peerID
});
// Listen for incoming connections
session.on('connection', function(connection) {
// Accept the connection
connection.accept();
// Set the data channel for the connection
dataChannel = connection.dataChannel;
});
// Update the message on the screen
document.getElementById('message').innerHTML = 'You are now hosting a session. Share the following peer ID with the other device: ' + peerID;
};
// Join a host
function joinHost() {
// Get the peer ID of the host device
var hostPeerID = document.getElementById('hostPeerID').value;
// Connect to the host device
peer.connect(hostPeerID);
// Listen for incoming connections
peer.on('connection', function(connection) {
// Accept the connection
connection.accept();
// Set the data channel for the connection
dataChannel = connection.dataChannel;
});
// Update the message on the screen
document.getElementById('message').innerHTML = 'You are now connected to the host device.';
};
// Send a message
function sendMessage() {
// Get the message from the text input
var message = document.getElementById('messageInput').value;
// Send the message to the other device
dataChannel.send(message);
// Clear the text input
document.getElementById('messageInput').value = '';
};
</script>
</body>
</html>
I would like to get an assistance on why my code is not working as expected and how it should be written.