提供: tty00

移動: 案内検索

はじめに

PeerJSはWebRTCのライブラリ。

開発環境

PeerServer

  • node.jsのnpmコマンド
npm install peer
  • サーバの起動
peerjs --debug --port 9000

サンプルコード

main.js

main = function() {
 
    var peer = new Peer(options = {host: 'localhost', port: 9000, path: '/'});
    var my_peer_id = null;
    var conn = null;
 
    //PeerServerに接続したときのイベント
    peer.on('open', function(id) {
        console.log('peer.on:open');
        my_peer_id = id;
        $('#my_peer_id').append( my_peer_id );
    });
 
    //別のpeerから接続されたときのイベント
    peer.on('connection', function(dest_conn) {
        console.log('peer.on:connection');
        //データを受信したときのイベント
        dest_conn.on('data', function(data) {
            console.log('dataConnection.on:data');
            var msg = '<p>' + data + '</p>';
            $('#console').append(msg);
            dest_conn.send('Hello! from ' + my_peer_id);
        }); 
    });
 
    peer.on('close', function() {
        console.log('peer.on:close');
    });
 
    peer.on('disconnected', function() {
        console.log('peer.on:disconnected');
    });
 
    $('#connect').click(function() {
        var dest_peer_id = $('#dest_peer_id').val();
        conn = peer.connect(dest_peer_id);
 
        //コネクションが確立したときのイベント
        conn.on('open', function() {
            console.log('dataConnection.on:open');
            conn.send('Hello! from ' + my_peer_id);
        });
 
        //コネクションが閉じたときのイベント
        conn.on('close', function() {
            console.log('dataConnection.on:close');
        });
 
        //データを受信したときのイベント
        conn.on('data', function(data) {
            console.log('dataConnection.on:data');
            var msg = '<p>' + data + '</p>';
            $('#console').append(msg);
        });
    });
};
 
$(main);

index.html

<html>
    <head>
        <title>PeerJS Sample</title>
        <script src="https://code.jquery.com/jquery-2.1.1.js"></script>
        <script src="http://cdn.peerjs.com/0.3/peer.js"></script>
        <script src="main.js"></script>
 
    </head>
 
    <body>
        <p><label id='my_peer_id'>My peer ID:</label></p>
        <form>
            <p><label>Dest peer ID<input id = 'dest_peer_id' type="text"></label></p>
            <p><input id = 'connect' type="button" value="接続"></p>
        </form>
 
        <div id ='console'></div>
 
    </body>
</html>