How can I receive data with a peerJS peer to peer connection?

白昼怎懂夜的黑 提交于 2019-12-06 04:17:52

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!');
};

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!