Node.js - 在同一端口上使用 Socket.io 和 Express

Node.js - Using Socket.io and Express on the Same Port

我需要重构此节点应用程序,以便 socket.io 和 express 使用相同的端口,我可以部署它。它目前按原样工作,但不会 运行 在 Heroku 上,除非所有东西都使用相同的端口。

var http = require('http');
var socket = require('socket.io');
var socketServer = http.createServer(app);
var io = socket.listen(socketServer);

var express = require('express');

var app = express();

var bodyParser = require('body-parser');
var path = require('path');

app.set('view engine', 'jade');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'public')));

var routes = require('./config/routes')(app, io);
var timer = require('./server/timer')(app, io);

var server = app.listen(process.env.PORT || 5000, function () {
    console.log('Server running on *:5000');
});

socketServer.listen(8000);

我也在学习节点,因此非常感谢任何关于一般重构的提示。

已编辑以匹配建议的解决方案: (Express 以这种方式工作,但会中断 socket.io)

var express = require('express');
var app = express();
var serv = require('http').createServer(app);
var io = require('socket.io').listen(serv);

var bodyParser = require('body-parser');
var path = require('path');

app.set('view engine', 'jade');

// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));

// parse application/json
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname, 'public')));

var routes = require('./config/routes')(app, io);
var timer = require('./server/timer')(app, io);

serv.listen(process.env.PORT || 5000, function () {
    console.log('Server running on *:' + (process.env.PORT || '5000'));
});

这是控制台中的新错误:

socket.io-1.3.4.js:2 GET http://localhost:8000/socket.io/?user=Trey&EIO=3&transport=polling&t=1424902016787-2

看起来 websockets 失败了,所以它又回到了长轮询,这也是失败的...

我认为这应该可行。

var express = require('express')
var app = express()
var server = require('http').createServer(app)
var io = require('socket.io')(server)

server.listen(80);

Heroku 也有一些关于这个主题的有用信息:heroku dev info websockets