3

peerJS を使用して 2 つのピアを接続しようとしています。私は彼らの「Getting Started」をほぼフォローしているだけですが、まだ苦労しています. 以下は、これまでに取得したコードです。

<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>

生成されたピア ID を使用して 2 つのピア間の接続を確立することができましたが、メッセージの送受信について理解できていないようです。私が理解できることから、 conn.send() はメッセージをクライアントに送信し、クライアントはそれを受信することになっていますが、他のピアに表示するデータを /get/ する方法がわかりません。最初のピアからの SendMessage 関数。私のコンピュータが窓の外に出る前に、誰かがデータがどのように送受信されるかを説明してもらえますか?

ありがとう

4

1 に答える 1