index.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. var express = require('express');
  2. var proto = require('./server');
  3. var util = require('./util');
  4. var http = require('http');
  5. var https = require('https');
  6. function ExpressPeerServer(server, options) {
  7. var app = express();
  8. util.extend(app, proto);
  9. options = app._options = util.extend({
  10. debug: false,
  11. timeout: 5000,
  12. key: 'peerjs',
  13. ip_limit: 5000,
  14. concurrent_limit: 5000,
  15. allow_discovery: false,
  16. proxied: false
  17. }, options);
  18. // Connected clients
  19. app._clients = {};
  20. // Messages waiting for another peer.
  21. app._outstanding = {};
  22. // Mark concurrent users per ip
  23. app._ips = {};
  24. if (options.proxied) {
  25. app.set('trust proxy', options.proxied);
  26. }
  27. app.on('mount', function() {
  28. if (!server) {
  29. throw new Error('Server is not passed to constructor - '+
  30. 'can\'t start PeerServer');
  31. }
  32. // Initialize HTTP routes. This is only used for the first few milliseconds
  33. // before a socket is opened for a Peer.
  34. app._initializeHTTP();
  35. app._setCleanupIntervals();
  36. app._initializeWSS(server);
  37. });
  38. return app;
  39. }
  40. function PeerServer(options, callback) {
  41. var app = express();
  42. options = options || {};
  43. var path = options.path || '/';
  44. var port = options.port || 80;
  45. delete options.path;
  46. if (path[0] !== '/') {
  47. path = '/' + path;
  48. }
  49. if (path[path.length - 1] !== '/') {
  50. path += '/';
  51. }
  52. var server;
  53. if (options.ssl) {
  54. if (options.ssl.certificate) {
  55. // Preserve compatibility with 0.2.7 API
  56. options.ssl.cert = options.ssl.certificate;
  57. delete options.ssl.certificate;
  58. }
  59. server = https.createServer(options.ssl, app);
  60. delete options.ssl;
  61. } else {
  62. server = http.createServer(app);
  63. }
  64. var peerjs = ExpressPeerServer(server, options);
  65. app.use(path, peerjs);
  66. if (callback) {
  67. server.listen(port, function() {
  68. callback(server);
  69. });
  70. } else {
  71. server.listen(port);
  72. }
  73. return peerjs;
  74. }
  75. exports = module.exports = {
  76. ExpressPeerServer: ExpressPeerServer,
  77. PeerServer: PeerServer
  78. };