Exemple #1
0
function createServerWithLibName(libName, requestListener) {
  var httpLib = require(libName);
  if (libName === "http") {
    return httpLib.createServer(requestListener);
  } else {
    return httpLib.createServer({key: key, cert: cert}, requestListener);
  }
}
  const server = (() => {
    if (!secure) {
      return createServer();
    }

    return createServer({
      key: fs.readFileSync(`${dirname}/server.key`),
      cert: fs.readFileSync(`${dirname}/server.crt`)
    });
  })();
Exemple #3
0
    const server = (() => {
      if (!tls) {
        return createServer(app.callback());
      }

      const options = {
        key: readFileSync(`${dirname}/server.key`),
        cert: readFileSync(`${dirname}/server.crt`)
      };

      return createServer(options, app.callback());
    })();
Exemple #4
0
	createWebSocketServer: function()
	{
	var
		secure = this.secure = ide.configuration.secure,
		http = require(secure ? 'https' : 'http'),
		onRequest = function(req, res) { res.end(); },
		server = secure ? http.createServer(secure, onRequest) :
			http.createServer(onRequest)
	;
		if (secure)
			this.log('Creating secure socket (https)');

		return server;
	}
Exemple #5
0
 createCAPIServer: function createCAPIServer(cb) {
     assert.equal(typeof (cb), 'function');
     var basePath = path.normalize(__dirname + '/../');
     var capi = require(basePath + '/capi/server.js');
     var config = capi.processConfigFile(CFG_FILE);
     // Don't initialize local server if remote is specified.
     if (config.host !== '127.0.0.1') {
         cb(null, {});
         return;
     }
     config.log = new Logger({
         name: 'capi',
         level: config.logLevel,
         stream: fs.createWriteStream(basePath + '/capi.log', {flags: 'a'}),
         serializers: restify.bunyan.serializers
     });
     var server = capi.createServer(config);
     server.connect(function (err) {
       if (err) {
         cb(err);
         return;
       }
       cb(null, server);
     });
 },
Exemple #6
0
		serverDomain.run(function() {
			var protocol = require(self.config.type);
			var server = self.server = protocol.createServer(function(req, res) {
				var reqd = Domain.create();
				var ctx= new Ctx(req, res, self);
				reqd.on("error", function(err) {
					console.log(err);
					self.emit("webError", err, ctx);
				});
				reqd.add(req);
				reqd.add(res);
				reqd.run(function() {
					self.onRequest(ctx);
				});
			});
			//设置超时时间
			server.timeout = self.config.timeout;
			//协议升级
			server.on("upgrade", function(req, socket, head) {
				//var latte = { req: req, res: res };
				self.onUpgrade(req, socket, head);
			});
			//绑定端口
			server.listen(self.config.port, function() {
				latte_lib.debug.info(self.config.port, "server start");
			});
		});
Exemple #7
0
es.pipeable = function () {
  console.error('warn: event-stream. I have decided that pipeable is a kitchen-sick and will remove soon if no objections')
  console.error('please post an issue if you actually use this. -- dominictarr')

  if(process.title != 'node')
    return console.error('cannot use es.pipeable in the browser')
  //(require) inside brackets to fool browserify, because this does not make sense in the browser.
  var opts = (require)('optimist').argv
  var args = [].slice.call(arguments)
  
  if(opts.h || opts.help) {
    var name = process.argv[1]
    console.error([
      'Usage:',
      '',
      'node ' + name + ' [options]',
      '  --port PORT        turn this stream into a server',
      '  --host HOST        host of server (localhost is default)',
      '  --protocol         protocol http|net will require(protocol).createServer(...',
      '  --help             display this message',
      '',
      ' if --port is not set, will stream input from stdin',
      '',
      'also, pipe from or to files:',
      '',
      ' node '+name+ ' < file    #pipe from file into this stream',
      ' node '+name+ ' < infile > outfile    #pipe from file into this stream',     
      '',
    ].join('\n'))
  
  } else if (!opts.port) {
    var streams = setup(args)
    streams.unshift(es.split())
    //streams.unshift()
    streams.push(process.stdout)
    var c = es.pipeline.apply(null, streams)
    process.openStdin().pipe(c) //there
    return c

  } else {
  
    opts.host = opts.host || 'localhost'
    opts.protocol = opts.protocol || 'http'
    
    var protocol = (require)(opts.protocol)
        
    var server = protocol.createServer(function (instream, outstream) {  
      var streams = setup(args)
      streams.unshift(es.split())
      streams.unshift(instream)
      streams.push(outstream || instream)
      es.pipe.apply(null, streams)
    })
    
    server.listen(opts.port, opts.host)

    console.error(process.argv[1] +' is listening for "' + opts.protocol + '" on ' + opts.host + ':' + opts.port)  
  }
}
Exemple #8
0
        'Mojito.Server is returned from createServer': function() {

            // Mock the server to avoid YUI loader/Resource store issues.
            Mojito.Server = function() {};

            server = Mojito.createServer();
            A.isObject(server);
            A.isInstanceOf(Mojito.Server, server);
        },
Exemple #9
0
es.pipeable = function () {
  var opts = require('optimist').argv
  var args = [].slice.call(arguments)
  
  if(opts.h || opts.help) {
    var name = process.argv[1]
    console.error([
      'Usage:',
      '',
      'node ' + name + ' [options]',
      '  --port PORT        turn this stream into a server',
      '  --host HOST        host of server (localhost is default)',
      '  --protocol         protocol http|net will require(protocol).createServer(...',
      '  --help             display this message',
      '',
      ' if --port is not set, will stream input from stdin',
      '',
      'also, pipe from or to files:',
      '',
      ' node '+name+ ' < file    #pipe from file into this stream',
      ' node '+name+ ' < infile > outfile    #pipe from file into this stream',     
      '',
    ].join('\n'))
  
  } else if (!opts.port) {
    var streams = setup(args)
    streams.unshift(es.split())
    //streams.unshift()
    streams.push(process.stdout)
    var c = es.connect.apply(null, streams)
    process.openStdin().pipe(c) //there
    return c

  } else {
  
    opts.host = opts.host || 'localhost'
    opts.protocol = opts.protocol || 'http'
    
    var protocol = require(opts.protocol)
        
    var server = protocol.createServer(function (instream, outstream) {  
      var streams = setup(args)
      streams.unshift(es.split())
      streams.unshift(instream)
      streams.push(outstream || instream)
      es.pipe.apply(null, streams)
    })
    
    server.listen(opts.port, opts.host)

    console.error(process.argv[1] +' is listening for "' + opts.protocol + '" on ' + opts.host + ':' + opts.port)  
  }
}
Service.prototype.start = function() {
    var self = this;
    this.server = server.createServer(this.config);

    // callback to propagate message arrival
    this.server.on(server.EVENT_RECEIVED_MESSAGE, function(message) {
        console.log('service receieved data:'+message);
        self.emit(EVENT_RECEIVED_MESSAGE, message);
    });

    this.server.start();
    this.clients = [];
}
Exemple #11
0
        'createServer() properly passes options': function() {
            var passed,
                options;

            // Mock the server type and capture options.
            Mojito.Server = function(options) {
                passed = options;
            };

            options = {'port': 2222};

            server = Mojito.createServer(options);
            OA.areEqual(options, passed);
        }
Exemple #12
0
exports.run = function(params, opts, callback) {
    var root = process.cwd(),
        store,
        appConfig,
        pack,
        inputOptions = opts || {},
        options = {},
        app;

    if (inputOptions.context) {
        inputOptions.context = utils.contextCsvToObject(inputOptions.context);
    }

    store = Store.createStore({
        root: root,
        preload: 'skip', // not need to preload, we only need appConfig and package.json
        context: inputOptions.context || {}
    });
    appConfig = store.getAppConfig();

    pack = store.config.readConfigJSON(path.join(root, 'package.json'));

    options.port = parseInt(params[0], 10) || appConfig.appPort;
    options.port = options.port || process.env.PORT || 8666;

    if (inputOptions.context) {
        options.context = inputOptions.context;
    }

    if (inputOptions.perf) {
        options.perf = inputOptions.perf;
    }

    app = Mojito.createServer(options);
    app.listen(null, null, function(err) {
        if (err) {
            utils.error('There was an error starting the application:\n');
            utils.error(err);
            console.log('\n');
            utils.error('Mojito was not started!\n', null, true);
            return;
        }
        console.log('\n');
        utils.success('\tMojito(v' + mojitoVersion + ') started' +
            (pack.name ? ' \'' + pack.name + '\'' : '') +
            ' on http://127.0.0.1:' + options.port + '/\n');
    });
};
Exemple #13
0
        adapter.getPort(settings.port, port => {
            if (parseInt(port, 10) !== settings.port && !adapter.config.findNextPort) {
                adapter.log.error('port ' + settings.port + ' already in use');
                process.exit(1);
            }
            settings.port = port;

            server.server = LE.createServer((req, res) => {
                res.writeHead(501);
                res.end('Not Implemented');
            }, settings, adapter.config.certificates, adapter.config.leConfig, adapter.log);

            server.server.listen(settings.port, (settings.bind && settings.bind !== '0.0.0.0') ? settings.bind : undefined);

            settings.crossDomain     = true;
            settings.ttl             = settings.ttl || 3600;
            settings.forceWebSockets = settings.forceWebSockets || false;

            server.io = new IOSocket(server.server, settings, adapter);
        });
Exemple #14
0
 createServer: function createServer(cb) {
     assert.equal(typeof (cb), 'function');
     // Don't initialize local server if remote is specified.
     if (CONFIG.host !== '127.0.0.1') {
         cb(null, {});
         return;
     }
     var basePath = path.normalize(__dirname + '/../');
     var ufds = require(basePath + '/lib/ufds');
     var config = ufds.processConfigFile(CFG_FILE);
     config.log =  new Logger({
         name: 'ufds',
         stream: fs.createWriteStream(basePath + '/ufds.log', {flags: 'a'}),
         serializers: {
             err: Logger.stdSerializers.err
         }
     });
     var server = ufds.createServer(config);
     server.init(function () {
         cb(null, server);
     });
 },
Exemple #15
0
var articulator = require(`${__dirname}/../index.js`);
var faker = require('faker');
var lodash = require('lodash');
var app = articulator.createServer(`${__dirname}/../example/api`, {
  faker,
  _: lodash,
  random_posts: function(num) {
    return lodash.times(num, () => ({
      id: faker.random.number(),
      title: faker.lorem.sentence()
    }));
  }
}, function(res){
  return { full_url: `http://example.local/${res.url}` };
});

if (require.main === module) {
  var port = process.env.PORT || 3000
  console.log(`\n  Running on: http://localhost:${port}`);
  app.listen(port);
}
Exemple #16
0
SCWorker.prototype._init = function (options) {
  var self = this;

  this.options = {};

  for (var i in options) {
    if (options.hasOwnProperty(i)) {
      this.options[i] = options[i];
    }
  }

  this.id = this.options.id;
  this.isLeader = this.id == 0;

  this._middleware = {};
  this._middleware[this.MIDDLEWARE_START] = [];

  if (this.options.downgradeToUser && process.setuid) {
    try {
      process.setuid(this.options.downgradeToUser);
    } catch (err) {
      this._errorDomain.emit('error', new InvalidActionError('Could not downgrade to user "' + this.options.downgradeToUser +
        '" - Either this user does not exist or the current process does not have the permission' +
        ' to switch to it.'));
    }
  }

  this.brokerEngine = require(this.options.brokerEngine);

  this._paths = options.paths;

  this._httpRequestCount = 0;
  this._wsRequestCount = 0;
  this._httpRPM = 0;
  this._wsRPM = 0;

  this.brokerEngineClient = new this.brokerEngine.Client({
    brokers: this.options.brokers,
    secretKey: this.options.secretKey
  });

  this.brokerEngineClient.on('error', function (err) {
    var error;
    if (typeof err == 'string') {
      error = new BrokerError(err);
    } else {
      error = err;
    }
    self._errorDomain.emit('error', error);
  });
  this.brokerEngineClient.on('warning', function () {
    self.warningHandler.apply(self, arguments);
  });
  this.exchange = this.global = this.brokerEngineClient.exchange();

  if (this.options.httpServerModule) {
    var httpServerFactory = require(this.options.httpServerModule);
    this.httpServer = httpServerFactory.createServer(this.options.protocolOptions);
  } else {
    if (this.options.protocol == 'https') {
      this.httpServer = https.createServer(this.options.protocolOptions);
    } else {
      this.httpServer = http.createServer();
    }
  }
  this.httpServer.on('request', this._httpRequestHandler.bind(this));
  this.httpServer.on('upgrade', this._httpRequestHandler.bind(this));

  this.httpServer.exchange = this.httpServer.global = this.exchange;

  var httpServerErrorDomain = domain.create();
  httpServerErrorDomain.add(this.httpServer);
  httpServerErrorDomain.on('error', function (err) {
    if (typeof err == 'string') {
      error = new HTTPServerError(err);
    } else {
      error = err;
    }
    self._errorDomain.emit('error', error);
  });

  var secure = this.options.protocol == 'https' ? 1 : 0;

  this.scServer = socketClusterServer.attach(this.httpServer, {
    brokerEngine: this.brokerEngineClient,
    wsEngine: this._paths.wsEnginePath,
    allowClientPublish: this.options.allowClientPublish,
    handshakeTimeout: this.options.handshakeTimeout,
    ackTimeout: this.options.ackTimeout,
    pingTimeout: this.options.pingTimeout,
    pingInterval: this.options.pingInterval,
    origins: this.options.origins,
    appName: this.options.appName,
    path: this.options.path,
    authKey: this.options.authKey,
    authPrivateKey: this.options.authPrivateKey,
    authPublicKey: this.options.authPublicKey,
    authAlgorithm: this.options.authAlgorithm,
    authDefaultExpiry: this.options.authDefaultExpiry,
    middlewareEmitWarnings: this.options.middlewareEmitWarnings,
    socketChannelLimit: this.options.socketChannelLimit,
    perMessageDeflate: this.options.perMessageDeflate
  });

  // Default authentication engine
  this.setAuthEngine(new AuthEngine());

  this.scServer.on('_connection', function (socket) {
    // The connection event counts as a WS request
    self._wsRequestCount++;
    socket.on('message', function () {
      self._wsRequestCount++;
    });
    self.emit(self.EVENT_CONNECTION, socket);
  });

  this.scServer.on('warning', function () {
    self.warningHandler.apply(self, arguments);
  });

  this._socketPath = this.scServer.getPath();
  this._socketPathRegex = new RegExp('^' + this._socketPath);

  this._errorDomain.add(this.scServer);

  this.scServer.on('ready', function () {
    self.emit(self.EVENT_READY);
  });
};
        break;
      case 'asc':
        chunk = new Array(len + 1).join('a');
        break;
    }
    chunks[t + '/' + k] = chunk;
  });
});

var server = http.createServer(function (req, res) {
  var parts = req.url.split('/');
  var t = parts[1], k = parts[2], c = parts[3], m = parts[4];
  var chunk = chunks[t + '/' + k];
  
  if (m === 'write') {
    res.write(chunk);
    res.end();
  }
  else {
    res.end(chunk);
  }
});

server.listen(0, function () {
  var href = 'http://localhost:' + server.address().port;
  types.forEach(function (t) {
    kbs.forEach(function (k) {
      cs.forEach(function (c) {
        methods.forEach(function (m) {
          console.log([ href, t, k, c, m ].join('/'));
        });
if (serverConfig.compress) {
  app.use(compress())
}

if (https) {
  var httpsConfig = {
    key: fs.readFileSync(path.resolve(__dirname, '../resources/hjs-webpack-localhost.key')),
    cert: fs.readFileSync(path.resolve(__dirname, '../resources/hjs-webpack-localhost.crt'))
  }

  if (typeof https === 'object') {
    assign(httpsConfig, https)
  }

  server = createServer(httpsConfig, app)
} else {
  server = createServer(app)
}

var compiler = webpack(config)

if (serverConfig.proxy) {
  if (!Array.isArray(serverConfig.proxy)) {
    serverConfig.proxy = [serverConfig.proxy]
  }
  serverConfig.proxy.forEach(function (proxyConfig) {
    var proxy = httpProxyMiddleware(proxyConfig.context, proxyConfig.options)
    app.use(function (req, res, next) {
      next()
    }, proxy)
Exemple #19
0
var ws = require(__dirname + '/node-websocket-server/lib/ws'),
    server = ws.createServer();

console.log('created server');

server.addListener("connection", function(conn){
  console.log('connection');

  conn.addListener("message", function(message){
    message = JSON.parse(message);
    message['id'] = conn.id
    conn.broadcast(JSON.stringify(message));
  });
});

server.addListener("close", function(conn){
  conn.broadcast(JSON.stringify({'id': conn.id, 'action': 'close'}));
});

server.listen(8000);

console.log('listening on port 8000');

    fs = require('fs'),
    url = require('url'),
    qs = require('querystring'),
    express = require('express'),
    iniparser = require('iniparser'),
    crypto = require('crypto'),
    i18n = require('i18n'),
    path = require('path');

console.log('Loading config');
var config = iniparser.parseSync('./config.ini');

// HTTP Server
var http = require(config.http.protocol);
var app = express();
var httpServer = http.createServer(app);
app.use(express.static(__dirname + config.filesystem.public_files));
app.set('views', __dirname + config.filesystem.view_files);
app.engine('html', require('ejs').renderFile);

// i18n config
i18n.configure({
    locales: ['en', 'de'],
    defaultLocale: config.locale.default,
    // See https://github.com/mashpie/i18n-node/issues/61
    directory: __dirname + '/locales',
    updateFiles: false
});
app.configure(function() {
    app.use(i18n.init);
});
Exemple #21
0
var cfg = require('./config');
var net = require(!cfg.ssl ? 'net' : 'tls');
var fstream = require('fs');
var crypt = require('crypto');
var svrUtils = require('./server_utils');

var server = null;
var hasLogging = false;

if (!cfg.ssl) {
	server = net.createServer(connectionHandler);
} else {
	server = net.createServer(cfg.sslOptions, connectionHandler);
}

server.on('listening', function () {
	console.log('Server started on %j', server.address());

	if (cfg.ssl) {
		console.log('Secured with SSL');
	}
});

server.on('error', function (err) {
	if (!hasLogging) {
		hasLogging = true;
		svrUtils.writeLog({
			doc_type: "log_receive",
			packet_type: null,
			stuff_type: null,
			src_packet_name: null,
Exemple #22
0
function start_server(config) {
  var
    server,
    fs = require('fs'),
    secure_server = config['ssl'],
    secure_client = config['remote-ssl'],
    proxy_server = require(secure_server ? 'https' : 'http'),
    proxy_client = require(secure_client ? 'https' : 'http');

  if (secure_server) {
    var options = {
      key: fs.readFileSync('privatekey.pem').toString(),
      cert: fs.readFileSync('certificate.pem').toString()
    };
    server = proxy_server.createServer(options, serve_request);
  } else {
    server = proxy_server.createServer(serve_request);
  }
  server.listen(config['port']);

  function serve_request(request, response) {
    var
      remote_host = config['remote-host'],
      delay = config['delay'] * 1000,
      start = Date.now(),
      response_status,
      response_headers,
      data = "";

    var options = {
      host: remote_host,
      method: request.method,
      path: request.url,
      headers: request.headers
    };

    process.stdout.write("-> http" + (secure_client ? 's' : '') + '://' + config['host'] + request.url + "...");
    proxy_request = proxy_client.request(options, handle_proxy_response);

    request.setEncoding('utf8');

    request.addListener('data', function(chunk) {
      proxy_request.write(chunk, 'binary');
    });

    request.addListener('end', function() {
      proxy_request.end();
    });

    function handle_proxy_response(proxy_response) {
      response_status = proxy_response.statusCode;
      response_headers = proxy_response.headers;
      
      proxy_response.addListener('data', function(chunk) {
        data += chunk;
      });

      proxy_response.addListener('end', function() {
        time_since_start = Date.now() - start;
        delay_left = delay - time_since_start;
        setTimeout(complete_response, delay_left);
      });
    }

    function complete_response() {
      response.writeHead(response_status, response_headers);
      response.write(data, 'utf8');
      response.end();
      console.log(" done");
    }
  }
}
Exemple #23
0
/*
var http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Hello World from NodeJS ... >>\n');
}).listen(8080);
console.log('Server running at http://46.137.53.149:8080/');
*/

var node_modules = '/usr/local/lib/node_modules/';
var express = require(node_modules+'express');
var app = express.createServer(),
    C   = require('./core');

app.use(express.bodyParser());
app.get('/', function(req, res){
  res.send('hello world ' +req.header('host'));
//  res.send(req.body.data);
//  console.log('Req >> ' +JSON.stringify(req, null, '\t') );
//  var C = req;
//  console.log(req);
});

app.listen(8080);
console.log('Server running at http://46.137.53.149:8080/');



Exemple #24
0
  return current_status(id, 'location', players);
}

function current_status(id, type, players) {
  var message = {
    id: id,
    type: type,
    players: players
  };

  return JSON.stringify(message);
}

var server = ws.createServer({
  debug: true
});

var players = {};

server.addListener("listening", function(){
  log("Listening for connections.");
});

// Handle WebSocket Requests
server.addListener("connection", function(conn){
  log("opened connection: "+conn.id);

  var response = handleEvent(conn.id, 'connection', false, players);
  server.send(conn.id, response);
Exemple #25
0
writeWebPagesToFiles = function(destination, urls, config, callback) {
    var options,
        userPages = {},
        i,
        app;

    if (config.urls) {
        // If the user is using builds.html5app.attachManifest or
        // .forceRelativePaths, we explicitly want to fix those URLs which are
        // pages (the ones they've specified).
        for (i = 0; i < config.urls.length; i += 1) {
            userPages[config.urls[i]] = true;
        }
    }

    options = {
        port: 11111,
        context: config.context
    };

    app = Mojito.createServer(options);

    app.listen(null, null, function(err) {
        var got = 0,
            need;

        if (err) {
            utils.error(err);
            return;
        }
        need = Object.keys(urls).length;

        Object.keys(urls).forEach(function(u) {
            var opts = {
                    headers: {
                        'x-mojito-build': 'html5app',
                        'x-mojito-build-path-to-root': pathTo('/',
                            libpath.dirname(urls[u]))
                    }
                };
            app.getWebPage(u, opts, function(err, url, content) {
                var dest;

                got += 1;

                if (err) {
                    utils.error('FAILED to get ' + url + ' with error:\n' +
                                err, null, true);
                } else {
                    if (config.attachManifest) {
                        content = attachManifest(destination, urls[url],
                            content,
                            userPages[url]);
                    }
                    if (config.forceRelativePaths) {
                        content = forceRelativePaths(destination, urls[url],
                            content,
                            userPages[url]
                            );
                    }
                    dest = libpath.join(destination, urls[url]);
                    mkdirP(libpath.dirname(dest), MODE_755);
                    fs.writeFileSync(dest, content, 'utf8');
                }

                if (got === need) {
                    app.close();
                    callback();
                }
            });
        });
    });
};
Exemple #26
0
var fs = require('fs');
var http = require('http');
var https = require('https');
var assert = require('assert');

var common = require(__dirname + '/common');
var httpolyglot = require(__dirname + '/../lib/index');

var srv = httpolyglot.createServer({
  key: fs.readFileSync(__dirname + '/fixtures/server.key'),
  cert: fs.readFileSync(__dirname + '/fixtures/server.crt')
}, common.mustCall(function(req, res) {
  this.count || (this.count = 0);
  res.end(req.socket.encrypted ? 'https' : 'http');
  if (++this.count === 2)
    this.close();
}, 2));
srv.listen(0, '127.0.0.1', common.mustCall(function() {
  var port = this.address().port;

  http.get({
    host: '127.0.0.1',
    port: port
  }, common.mustCall(function(res) {
    var body = '';
    res.on('data', function(data) {
      body += data;
    }).on('end', common.mustCall(function() {
      assert.strictEqual(body, 'http');
    }));
  }));
Exemple #27
0
var express = require(__dirname + '/node_modules/express/');
var app = express.createServer(express.static(__dirname + '/public'));
var os = require('os');
var io = require(__dirname + '/node_modules/socket.io/').listen(app);

app.listen(process.env.PORT || 1337);
// List off all sockets
var sockets = {};

// I hope this will match the heroku hostname.
// If you are not going to use heroku just remove this block
// I need this because heroku does not support websockets
// so I have to force socket.io to long-polling
if(os.hostname().match(/\d+\-\d+/)){
    io.configure(function(){
        io.set("transports", ["xhr-polling"]); 
        io.set("polling duration", 10); 
    });
}

io.sockets.on('connection', function(socket) {
    //keep everyone in a list
    sockets[socket.id] = socket; 
    
    var onJoin = function(data){
        var list = []; // Create a participant list
        
        // Go through all sockets and tell them 
        // this new person has joined the chat
        for (var id in sockets) {
            socket.name = data.name; // Keep the entered name in socket data
Exemple #28
0
/**
 * Created by gbox3d on 2014. 5. 29..

 npm install sockjs

 */

var theApp = {
    version: '0.0.2',
    module_path: '/usr/local/lib/node_modules/'
}
var http = require('http');
var sockjs = require(theApp.module_path +  'sockjs');

var echo = sockjs.createServer();
echo.on('connection', function(conn) {


    conn.write('welcome!');


    conn.on('data', function(message) {

        conn.write(message);


    });
    conn.on('close', function() {

        console.log('connection closed');
Exemple #29
0
        } catch (e) {}

        response.writeHead(200);
        response.write(file, 'utf8');
        response.end();
    });
}

var app;

if (isUseHTTPs) {
    var options = {
        key: fs.readFileSync(path.join(__dirname, 'fake-keys/privatekey.pem')),
        cert: fs.readFileSync(path.join(__dirname, 'fake-keys/certificate.pem'))
    };
    app = server.createServer(options, serverHandler);
} else app = server.createServer(serverHandler);

app = app.listen(port, process.env.IP || '0.0.0.0', function() {
    var addr = app.address();
    console.log('El servidor escucha', addr.address + ':' + addr.port);
});

require('./Signaling-Server.js')(app, function(socket) {
    try {
        var params = socket.handshake.query;

        // "socket" object is totally in your own hands!
        // do whatever you want!

        // in your HTML page, you can access socket as following:
const app = require(`./lib/app`);
const http = require(`http`);
const port = process.env.PORT || 3000;
require(`./lib/mongoose-setup`);

const server = http.createServer(app);

server.listen(port, () => {
  console.log('server is running at ', server.address());
});



module.exports = server;