我正在尝试创建自己的PeerJS服务器

时间:2018-01-30 11:30:52

标签: javascript node.js express webrtc peerjs

以下是代码,但我不知道我缺少什么

index.js (就像服务器一样)

var path = require('path');
var express = require('express');

var routes = require('./routes');

var app = express();
app.use('/', routes);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');

srv = app.listen(process.env.PORT)
app.use('./peerjs', require('peer').ExpressPeerServer(srv, {
    debug: true
}));

srv.listen(process.env.PORT || 3000, function(){
  console.log("Express server listening on port %d in %s mode", this.address().port, app.settings.env);
});

app.js (主js文件)

navigator.getUserMedia = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia);
//get browser cmopt

var me = {};
var myStream;
var peers = {};

init();

function init() {
  if (!navigator.getUserMedia) return unsupported();

  getLocalAudioStream(function(err, stream) {
    if (err || !stream) return;

    connectToPeerJS(function(err) {
      if (err) return;

      registerIdWithServer(me.id);
      if (call.peers.length) callPeers();
      else displayShareMessage();
    });
  });
} // initialization


function connectToPeerJS(cb) {
  display('Connecting to PeerJS...');
//  me = new Peer({key: API_KEY});
  var peer = new Peer({
    host: location.hostname,
    port: location.port || (location.protocol === 'https://rapidcom.herokuapp.com' ? 9000 : 80),
    path: '/peerjs'
});
  me.on('call', handleIncomingCall);

  me.on('open', function() {
    display('Connected.');
    display('ID: ' + me.id);
    cb && cb(null, me);
  });// connect to peerJs Server and get ID From the Server

  me.on('error', function(err) {
    display(err);
    cb && cb(err);
  });
}


function registerIdWithServer() {
  display('Registering ID with server...');
  $.post('/' + call.id + '/addpeer/' + me.id);
} // Add our ID to the list of PeerJS IDs for this call


function unregisterIdWithServer() {
  $.post('/' + call.id + '/removepeer/' + me.id);
}


function callPeers() {
  call.peers.forEach(callPeer);
}

function callPeer(peerId) {
  display('Calling ' + peerId + '...');
  var peer = getPeer(peerId);
  peer.outgoing = me.call(peerId, myStream);

  peer.outgoing.on('error', function(err) {
    display(err);
  });

  peer.outgoing.on('stream', function(stream) {
    display('Connected to ' + peerId + '.');
    addIncomingStream(peer, stream);
  });
}


function handleIncomingCall(incoming) {
  display('Answering incoming call from ' + incoming.peer);
  var peer = getPeer(incoming.peer);
  peer.incoming = incoming;
  incoming.answer(myStream);
  peer.incoming.on('stream', function(stream) {
    addIncomingStream(peer, stream);
  });
}// When someone initiates a call via PeerJS

// Add the new audio stream. Either from an incoming call, or from the response to one of our outgoing calls
function addIncomingStream(peer, stream) {
  display('Adding incoming stream from .... ' + peer.id);
  peer.incomingStream = stream;
  playStream(stream);
}


function playStream(stream) {
  var audio = $('<audio autoplay />').appendTo('body');
  audio[0].src = (URL || webkitURL || mozURL).createObjectURL(stream);
}


function getLocalAudioStream(cb) {
  display('Trying to access your microphone. Please click "Allow".');

  navigator.getUserMedia (
    {video: false, audio: true},

    function success(audioStream) {
      display('Microphone is open.');
      myStream = audioStream;
      if (cb) cb(null, myStream);
    },

    function error(err) {
      display('Couldn\'t connect to microphone. Reload the page to try again.');
      if (cb) cb(err);
    }
  );
}

function getPeer(peerId) {
  return peers[peerId] || (peers[peerId] = {id: peerId});
}

function displayShareMessage() {
  display('Give someone this URL to chat.');
  display('<input type="text" value="' + location.href + '" readonly>');

  $('#display input').click(function() {
    this.select();
  });
}

function unsupported() {
  display("Your browser doesn't support getUserMedia.");
}

function display(message) {
  $('<div />').html(message).appendTo('#display');
}

Config.js

{ 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] };

routes.js

var express = require('express');
var router = express.Router();

var config = require('./config');
var Call = require('./call'); 
// Create a new Call instance, and redirect
router.get('/new', function(req, res) {
  var call = Call.create();
  res.redirect('/' + call.id);
});

// Add PeerJS ID to Call instance when someone opens the page
router.post('/:id/addpeer/:peerid', function(req, res) {
  var call = Call.get(req.param('id'));
  if (!call) return res.status(404).send('Call not found');
  call.addPeer(req.param('peerid'));
  res.json(call.toJSON());
});

// Remove PeerJS ID when someone leaves the page
router.post('/:id/removepeer/:peerid', function(req, res) {
  var call = Call.get(req.param('id'));
  if (!call) return res.status(404).send('Call not found');
  call.removePeer(req.param('peerid'));
  res.json(call.toJSON());
});

// Return JSON representation of a Call
router.get('/:id.json', function(req, res) {
  var call = Call.get(req.param('id'));
  if (!call) return res.status(404).send('Call not found');
  res.json(call.toJSON());
});

// Render call page
router.get('/:id', function(req, res) {
  var call = Call.get(req.param('id'));
  if (!call) return res.redirect('/new');

  res.render('call', {
    apiKey: config.peerjs.key,
    call: call.toJSON()
  });
});

// Landing page
router.get('/', function(req, res) {
  res.render('index');
});

module.exports = router;

Call.js (html文件)

<!DOCTYPE html>
<html>
<head>
  <title>Rapidcom</title>
</head>
<body>
  <div class="wrapper">
    <div id="display"></div>
  </div>

  <footer>
    <div class="wrapper">
      <a href="/new"> ~~~~~Start another call~~~~~~~</a>
    </div>
  </footer>

   var peer = new Peer( id,{ host: 'https://rapidcom.herokuapp.com', port: 9000, path: '.public/app' });
    window.call = <%- JSON.stringify(call, null, 2) %>;


</script>

  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="/app.js"></script>
  <script src="/peer.js"></script>
</body>
</html>

此外我还在heroku上托管了PeerJs服务器,请帮助我创建这个,我不知道我被困在哪里。我尝试拉每一个字符串,但没有得到这样的错误。

TypeError:无法读取属性&#39; key&#39;未定义的    在C:\ Users \ Windows \ Desktop \ RapidComNew \ routes.js:41:27    在Layer.handle [as handle_request](C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ layer.js:82:5)    在下一个(C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ route.js:100:13)    在Route.dispatch(C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ route.js:81:3)    在Layer.handle [as handle_request](C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ layer.js:82:5)    在C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ index.js:233:24    在param(C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ index.js:330:14)    在param(C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ index.js:346:14)    在Function.proto.process_params(C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ index.js:390:3)    在C:\ Users \ Windows \ Desktop \ RapidComNew \ node_modules \ express \ lib \ router \ index.js:227:12

1 个答案:

答案 0 :(得分:1)

在app.js而不是

var peer = new Peer({
    host: location.hostname,
    port: location.port || (location.protocol === 'https://rapidcom.herokuapp.com' ? 9000 : 80),
    path: '/peerjs'
});

添加了这个

  me = new Peer({ host:'rapidserver.herokuapp.com', secure:true, port:443, key: 'peerjs', debug: 3})