server.address()。port正在获取nodejs中的随机端口地址

时间:2014-09-21 23:07:08

标签: node.js

即使我将端口地址定义为8200,我也会得到随机端口地址。如何明确地将server.address()。port定义为8200

var express = require('express')
        //Required for cluster 
        ,
        cluster = require('cluster')
        //Required for countting the cpu cores 
        ,
        numCPUs = require('os').cpus().length,
        socketio = require('socket.io'),
        routes = require('./routes'),
        user = require('./routes/user'),
        https = require('https'),
        connect = require('connect'),
        fs = require('fs'),
        app = connect(),
        sslOptions, server,
        PORT = 8200,


        path = require('path');



sslOptions = {
        key: fs.readFileSync('./ssl/ecssl/server-key.pem'),
        cert: fs.readFileSync('./ssl/ecssl/server-cert.pem')
};

if (cluster.isMaster) {

        for (var i = 1; i < numCPUs; ++i)
                console.log('hi');
        cluster.fork();
        cluster.on('online', function(worker) {
                console.log("The Master is forked");
        });
        console.log('hi');
        cluster.on('exit', function(worker, code, signal) {
                logger.log('worker ' + worker.process.pid + ' died');
        });
} else {
        //console.log('hi');
        var app = express();
        var server = require('https').createServer(sslOptions, app).listen(app.get('port'), function() {
                //server.address().port = 1111;

                console.log('Listening on https://' + server.address().address + ':' + server.address().port);

                //console.log('listening on https://' +server.listen(PORT, HOST);
                //console.log("Express server listening on port " + app.get('port'));
        });


        // all environments
        //server.set('port', process.env.PORT || 8200 );
        app.set('port', process.env.PORT || 8200);
        app.set('views', __dirname + '/views');
        app.set('view engine', 'ejs');
        app.use(express.favicon());
        app.use(express.logger('dev'));
        app.use(express.bodyParser());
        app.use(express.methodOverride());
        app.use(app.router);
        app.use(express.static(path.join(__dirname, 'public')));



        // development only
        if ('development' == app.get('env')) {

                app.use(express.errorHandler());
        }

        app.get('/', routes.index);
        app.get('/users', user.list);

2 个答案:

答案 0 :(得分:1)

在您开始收听之前,您还没有设置端口。端口未定义,因此您可以获得随机端口。

答案 1 :(得分:0)

你的问题就在这一行:

var server = require('https').createServer(sslOptions, app).listen(app.get('port'), function() {

您需要移动此部分:

// all environments //server.set('port', process.env.PORT || 8200 ); app.set('port', process.env.PORT || 8200);

到文件的顶部,以便app.get(&#39; port&#39;)可以返回一些内容。