2015-08-23 30 views
8

WebRTC DataChannels ile tarayıcıdan tarayıcıya (p2p) JSON mesajlarının iletişimini yürütmekle ilgilenen geliştiricilerin güncel tutulabilmesi için bu, bir Community Wiki post haline gelmektir. basit ama işlevsel örneklere sahip olmak.Hello World WebRTC DataChannel Sinyal Uygulaması Uygulandı

WebRTC DataChannels deneyseldir ve hala taslaktır. Görünüşe göre şu anda web, eski bir WebRTC örneklerinin bir mayın tarlası ve daha da fazlası, bir geliştirici RTCDataChannel API'sini öğrenmeye çalışıyorsa.

Bugün WebRTC compliant browsers arasında çalışan basit ancak işlevsel 1 sayfalık örnekler bulmak zor görünüyor. Örneğin, some examples bir sinyalizasyon uygulamasını bırakır, sadece tek bir tarayıcı (örneğin Chrome-Chrome) için others, many güncel API değişiklikleri nedeniyle güncelliğini kaybeder ve others o kadar karmaşıktır ki başlamak için bir engel oluştururlar.

  1. İstemci tarafı kodu (200 satır veya daha az)
  2. Sunucu tarafı kod 1-sayfası edilir:

    (bir şey yerine getirilmediği takdirde lütfen belirtin) Aşağıdaki ölçütleri karşılayan örnekler sonrası Lütfen 1 sayfalık ve teknoloji çalışır (örneğin node.js, php, python, vb)

  3. Sinyal mekanizması (vb GCM, long polling, örneğin Yuvalarının) uygulanır ve protokol teknolojisi başvurulmaktadır
  4. Çalışma kod başvuruda bulunulan tarayıcılar arası (Chrome, Firefox, Opera, ve/veya Bowser)
  5. Minimal seçenekleri, hata işleme, abstraction vb - niyet
  6. İşte

cevap

4

sinyalizasyon ve düğüm için HTML5 WebSockets kullanan bir çalışma örneği bir ilköğretim örnektir WebSockets
istemci: pure html/javascript
sunucusu: ws
son test node.js:arka uç

sinyalizasyon teknolojisi .js, Chrome 44.0.2403.157 m, Opera 31.0.1889.174


istemci tarafı kodu:

<html> 
<head> 
</head> 
<body> 
    <p id='msg'>Click the following in different browser windows</p> 
    <button type='button' onclick='init(false)'>I AM Answerer Peer (click first)</button> 
    <button type='button' onclick='init(true)'>I AM Offerer Peer</button> 

<script> 
    (function() { 
     var offererId = 'Gandalf', // note: client id conflicts can happen 
      answererId = 'Saruman', //  no websocket cleanup code exists 
      ourId, peerId, 
      RTC_IS_MOZILLA = !!window.mozRTCPeerConnection, 
      RTCPeerConnection = window.RTCPeerConnection || window.webkitRTCPeerConnection || window.mozRTCPeerConnection || window.msRTCPeerConnection, 
      RTCSessionDescription = window.RTCSessionDescription || window.mozRTCSessionDescription || window.msRTCSessionDescription, 
      RTCIceCandidate = window.RTCIceCandidate || window.mozRTCIceCandidate || window.msRTCIceCandidate, 
      rtcpeerconn = new RTCPeerConnection(
        {iceServers: [{ 'url': 'stun:stun.services.mozilla.com'}, {'url': 'stun:stun.l.google.com:19302'}]}, 
        {optional: [{RtpDataChannels: false}]} 
       ), 
      rtcdatachannel, 
      websocket = new WebSocket('ws://' + window.location.hostname + ':8000'), 
      comready, onerror; 

     window.init = function(weAreOfferer) { 
      ourId = weAreOfferer ? offererId : answererId; 
      peerId = weAreOfferer ? answererId : offererId; 

      websocket.send(JSON.stringify({ 
       inst: 'init', 
       id: ourId 
      })); 

      if(weAreOfferer) { 

       rtcdatachannel = rtcpeerconn.createDataChannel(offererId+answererId); 
       rtcdatachannel.onopen = comready; 
       rtcdatachannel.onerror = onerror; 

       rtcpeerconn.createOffer(function(offer) { 
        rtcpeerconn.setLocalDescription(offer, function() { 
         var output = offer.toJSON(); 
         if(typeof output === 'string') output = JSON.parse(output); // normalize: RTCSessionDescription.toJSON returns a json str in FF, but json obj in Chrome 

         websocket.send(JSON.stringify({ 
          inst: 'send', 
          peerId: peerId, 
          message: output 
         })); 
        }, onerror); 
       }, onerror); 
      } 
     }; 

     rtcpeerconn.ondatachannel = function(event) { 
      rtcdatachannel = event.channel; 
      rtcdatachannel.onopen = comready; 
      rtcdatachannel.onerror = onerror; 
     }; 

     websocket.onmessage = function(input) { 
      var message = JSON.parse(input.data); 

      if(message.type && message.type === 'offer') { 
       var offer = new RTCSessionDescription(message); 

       rtcpeerconn.setRemoteDescription(offer, function() { 
        rtcpeerconn.createAnswer(function(answer) { 
         rtcpeerconn.setLocalDescription(answer, function() { 
          var output = answer.toJSON(); 
          if(typeof output === 'string') output = JSON.parse(output); // normalize: RTCSessionDescription.toJSON returns a json str in FF, but json obj in Chrome 

          websocket.send(JSON.stringify({ 
           inst: 'send', 
           peerId: peerId, 
           message: output 
          })); 
         }, onerror); 
        }, onerror);     
       }, onerror); 
      } else if(message.type && message.type === 'answer') {    
       var answer = new RTCSessionDescription(message); 
       rtcpeerconn.setRemoteDescription(answer, function() {/* handler required but we have nothing to do */}, onerror); 
      } else if(rtcpeerconn.remoteDescription) { 
       // ignore ice candidates until remote description is set 
       rtcpeerconn.addIceCandidate(new RTCIceCandidate(message.candidate)); 
      } 
     }; 

     rtcpeerconn.onicecandidate = function (event) { 
      if (!event || !event.candidate) return; 
      websocket.send(JSON.stringify({ 
       inst: 'send', 
       peerId: peerId, 
       message: {candidate: event.candidate} 
      })); 
     }; 

     /** called when RTC signaling is complete and RTCDataChannel is ready */ 
     comready = function() { 
      rtcdatachannel.send('hello world!'); 
      rtcdatachannel.onmessage = function(event) { 
       document.getElementById('msg').innerHTML = 'RTCDataChannel peer ' + peerId + ' says: ' + event.data;  
      } 
     }; 

     /** global error function */ 
     onerror = websocket.onerror = function(e) { 
      console.log('====== WEBRTC ERROR ======', arguments); 
      document.getElementById('msg').innerHTML = '====== WEBRTC ERROR ======<br>' + e; 
      throw new Error(e); 
     }; 
    })(); 
</script> 
</body> 
</html>

sunucu tarafı kod: Hata WebSocket'e alınıyor

var server = require('http').createServer(), 
    express = require('express'),  
    app = express(), 
    WebSocketServer = require('ws').Server, 
    wss = new WebSocketServer({ server: server, port: 8000 }); 

app.use(express.static(__dirname + '/static')); // client code goes in static directory 

var clientMap = {}; 

wss.on('connection', function (ws) { 
    ws.on('message', function (inputStr) { 
     var input = JSON.parse(inputStr); 
     if(input.inst == 'init') { 
      clientMap[input.id] = ws; 
     } else if(input.inst == 'send') { 
      clientMap[input.peerId].send(JSON.stringify(input.message)); 
     } 
    }); 
}); 

server.on('request', app); 
server.listen(80, YOUR_HOSTNAME_OR_IP_HERE, function() { console.log('Listening on ' + server.address().port) });
+0

KAPAMA veya KAPALI durumda zaten – Wajihurrehman

+0

alma hatası WebSocket olduğunu zaten KAPALI veya KAPALI durumunda.() {: 'Init', id ourId inst} JSON.stringify(); websocket.send neden bu kod satırında söyler misiniz Websockets ile yeni ve wrtc iki iki dosya oluşturmak için bir ön sunucu ve istemci için bir html dosyası ve iki farklı tarayıcıda açın. – Wajihurrehman

İlgili konular