2015-08-23 11 views
8

L'intento è quello di diventare un post Community Wiki aggiornato così gli sviluppatori interessati ad implementare la comunicazione dei messaggi JSON browser-to-browser (p2p) con WebRTC DataChannels avere esempi semplici ma funzionali.Working Hello World WebRTC Esempi di DataChannel con segnalazione implementata

WebRTC DataChannels sono sperimentali e ancora in fase di bozza. Sembra che attualmente il web sia un campo minato di esempi WebRTC obsoleti e ancora di più se uno sviluppatore sta cercando di imparare l'API RTCDataChannel.

Gli esempi di 1 pagina semplici ma funzionali che funzionano oggi su WebRTC compliant browsers sembrano molto difficili da trovare. Ad esempio, some examples omette un'implementazione di segnalazione, others funziona solo per un singolo browser (ad esempio Chrome-Chrome), many non sono aggiornati a causa delle recenti modifiche API e others sono così complessi che creano una barriera per iniziare.

Si prega di inviare esempi che soddisfano i seguenti criteri (se qualcosa non è soddisfatta si prega di specificare):

  1. codice lato client è di 1 pagina (200 linee o meno)
  2. codice lato server è 1-page e la tecnologia viene fatto riferimento (ad esempio Node.js, PHP, Python, ecc)
  3. meccanismo di segnalazione è implementato e la tecnologia del protocollo si fa riferimento (ad es WebSockets, long polling, GCM, etc.)
  4. codice di lavoro che viene eseguito cross-browser (Chrome, Firefox, Opera, e/o Bowser)
  5. opzioni minime, la gestione degli errori, abstraction, ecc - l'intento è un esempio elementare

risposta

4

Ecco un esempio di lavoro che utilizza HTML5 WebSocket per la segnalazione e un nodo .js backend

segnalazione tecnologia: WebSockets
cliente: pure html/javascript
server: node.js, ws
ultima testato su: 01.237.878,090786 millions, Chrome 44.0.2403.157 m, Opera 31.0.1889.174


codice lato client:

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

codice lato server:

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

Ottenere errore WebSocket è già in chiusura o stato CLOSED – Wajihurrehman

+0

ottenere WebSocket errore viene già in stato CHIUSURA o CHIUSO. su questa riga di codice, la prego di dirmi perché websocket.send (JSON.stringify ({ inst: 'init', id: Ourid })); Sono nuovo con websockets e wrtc creare due due file un server anteriore e un file html per client e aperto in due diversi browser. – Wajihurrehman