2015-05-20 3 views
0

Я создаю webapp с peer.js. Это приложение, в котором вы можете видеть друг друга через веб-камеру, просто отправив идентификатор от другого человека через сервер из peer.js.Отправка переменной через peer.js

Это работает неплохо, но я хочу, чтобы иметь возможность отправлять переменную другому человеку. Причина, по которой я хочу это, заключается в том, что я хочу создать кнопку, которая всякий раз, когда она нажата, другой человек слышит звук.

Как:

$('.button').click(function() 
{ 
    var clicked = true; 
    //send var clicked to the other person so I can use an if statement there 
} 

У меня есть 2 проблемы. Я не знаю, как отправить эту переменную другому человеку через одноранговый сервер, и это сделано с помощью jquery, поэтому я не уверен, могу ли я использовать переменную в качестве глобальной переменной для кода javascript.

<script> 
    $(document).ready(function() { 
     $('.controls').hide(); 
     $('.bovenlijst').hide(); 
     $('.fotomaken').hide(); 
    }); 
    // Compatibility shim 
    navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; 

    // PeerJS object 
    var peer = new Peer({ key: 'lwjd5qra8257b9', debug: 3, config: {'iceServers': [ 
     { url: 'stun:stun.l.google.com:19302' } // Pass in optional STUN and TURN server for maximum network compatibility 
    ]}}); 


    peer.on('open', function(){ 
     $('#my-id').text(peer.id); 
     console.log(peer.id); 
    }); 

    // Receiving a call 
    peer.on('call', function(call){ 
     // Answer the call automatically (instead of prompting user) for demo purposes 
     call.answer(window.localStream); 
     step3(call); 
    }); 
    peer.on('error', function(err){ 
     alert(err.message); 
     // Return to step 2 if error occurs 
     step2(); 
    }); 

    // Click handlers setup 
    $(function(){ 
     $('#make-call').click(function(){ 
     // Initiate a call! 
     var call = peer.call($('#callto-id').val(), window.localStream); 
     $('#step2').hide(); 
     $('.controls').show(); 
     $('.bovenlijst').show(); 
     $('.fotomaken').show(); 
     step3(call); 

     }); 

     $('#end-call').click(function(){ 
     window.existingCall.close(); 
     step2(); 
     }); 

     // Retry if getUserMedia fails 
     $('#step1-retry').click(function(){ 
     $('#step1-error').hide(); 
     step1(); 
     }); 

     // Get things started 
     step1(); 
    }); 

    function step1() { 
     // Get audio/video stream 
     navigator.getUserMedia({audio: true, video: true}, function(stream){ 
     // Set your video displays 
     $('#my-video').prop('src', URL.createObjectURL(stream)); 

     window.localStream = stream; 
     step2(); 
     }, function(){ $('#step1-error').show(); }); 
    } 

    function step2() { 
     $('#step1, #step3').hide(); 
     $('#step2').show(); 
    } 

    function step3 (call) { 
     // Hang up on an existing call if present 
     if (window.existingCall) { 
     window.existingCall.close(); 
     } 

     // Wait for stream on the call, then set peer video display 
     call.on('stream', function(stream){ 
     $('#their-video').prop('src', URL.createObjectURL(stream)); 
     }); 

     // UI stuff 
     window.existingCall = call; 
     $('#their-id').text(call.peer); 
     call.on('close', step2); 
     $('#step1, #step2').hide(); 
     $('#step3').show(); 
    } 

    </script> 

ответ

1

Все, что вам нужно сделать, это открыть дополнительно к мультимедийному соединению соединение для передачи данных другому партнеру. Таким образом вы можете передавать данные как переменные между клиентами. Эта функция включена в состав PeerJS.

Из документации продлен с использованием переменной:

Connect:

var myVariable = 'this is a test'; 
var conn = peer.connect('another-peers-id'); 
conn.on('open', function(){ 
    conn.send(myVariable); 
}); 

Получить

peer.on('connection', function(conn) { 
    conn.on('data', function(data){ 
    // Will print 'this is a test' 
    console.log(data); 
    }); 
}); 

Смотрите также на http://peerjs.com/