我正在尝试使用socket.io和express.js
创建一个集群服务器。我正在youtube上关注互联网上的各种教程。
我目前所拥有的是app.js
中的代码:
var cluster = require('cluster');
if (cluster.isMaster) {
var cpuCount = require('os').cpus().length;
var workers = [];
for (var i = 0; i < cpuCount; i++) {
workers[i] = cluster.fork();
}
cluster.on('exit', function (worker){
for (var i = 0; i < workers.length; i++) {
if (worker.process.pid === workers[i].process.pid) {
workers.splice(i, 1);
}
}
for (var i = 0; i < cpuCount - workers.length; i++) {
workers.push(cluster.fork());
}
});
} else {
/**
* Module dependencies.
*/
var express = require('express');
var routes = require('./routes');
var http = require('http');
var path = require('path');
var app = express();
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
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);
var server = http.createServer(app);
var io = require('socket.io').listen(app.get('port'));
}
当我转到http://localhost:3000/
时,我得到了回复:
欢迎使用socket.io。
在我以前的测试脚本中,我没有遇到这个问题,我的jade模板也很好。有人能解释为什么会这样吗?
此外,在我的路线目录中,我有脚本:index.js,代码如下:
/*
* GET home page.
*/
exports.index = function(req, res){
res.render('index', { title: 'Express' });
};
最后在我的views文件夹中,我有layout.jade:
doctype 5
html
head
title= title
link(rel='stylesheet', href='/stylesheets/style.css')
body
block content
和index.jade:
extends layout
block content
h1= title
p Welcome to #{title}
答案 0 :(得分:1)
似乎问题出现在app.js的最后几行
这解决了这个问题:
var server = http.createServer(app);
var io = require('socket.io').listen(server);
server.listen(app.get('port'));
很抱歉给您带来不便。