I'm trying to connect two peers using peerJS. I am pretty much just following through their "Getting Started" but I am still struggling. Below is the code that I have gotten so far.
<body>
<script src="http://cdn.peerjs.com/0.3/peer.min.js"></script>
<script>
var conn;
var peer = new Peer({key: 'lwjd5qra8257b9'});
peer.on('open', function(id){
console.log('My peer ID is:' + id);
document.getElementById('peerIdDisplay').innerHTML = '<b>My peer ID is: </b><font color="red">' + id + '</font>';
});
function ConnectToPeer()
{
var peerId = document.getElementById("peerIdTxtBox").value;
console.log(peerId);
conn = peer.connect(peerId);
AfterConnInit();
peer.on('error', function(err){
console.log('error');
});
};
peer.on('connection', function(conn)
{
console.log('connected');
});
function AfterConnInit()
{
conn.on('open', function() {
// receive messages
conn.on('data', function(data) {
console.log('received', data);
});
//send messages
conn.send('hello');
});
};
function SendMessage()
{
//conn.send('Hello!');
};
</script>
<p id='peerIdDisplay' style='font-family:verdana'><b>My peer ID is: </b></p>
<hr style='width:100%'/>
<p id='instructions'>Enter another peer's ID to connect to them..</p>
<form>
<input type="text" id="peerIdTxtBox">
</form>
<button id="conToPeerBtn" OnClick="ConnectToPeer()">Connect To Peer</button>
<button id="sendMessageBtn" OnClick="SendMessage()">Send Message</button>
</body>
I have managed to get a connection between the two peers using a generated peerID, however, I can't seem to get my head around sending and receiving messages. From what I can understand the conn.send() is supposed to send the message to the client which then receives it, but I don't know how to /get/ the data to display on the other peer, let alone send it using a SendMessage function from the first peer. Can someone PLEASE explain how the data is sent and received before my computer goes out the window?
Thanks
The 'data'
event was being listened inside the conn.on('open')
, moving it as an independent event handler will get the code working.
Below is the modified code
<script>
var conn;
var peer = new Peer({key: 'lwjd5qra8257b9'});
peer.on('open', function(id){
console.log('My peer ID is:' + id);
document.getElementById('peerIdDisplay').innerHTML = '<b>My peer ID is: </b><font color="red">' + id + '</font>';
});
function ConnectToPeer()
{
var peerId = document.getElementById("peerIdTxtBox").value;
console.log(peerId);
conn = peer.connect(peerId);
peer.on('error', function(err){
console.log('error');
});
};
peer.on('connection', function(conn)
{
console.log('peer connected');
conn.on('open', function() {
console.log('conn open');
});
conn.on('data', function(data) {
console.log(data);
});
});
function SendMessage()
{
conn.send('Hello!');
};
来源:https://stackoverflow.com/questions/20166067/how-can-i-receive-data-with-a-peerjs-peer-to-peer-connection