5

I need to refactor this node app so socket.io and express use the same port and I can deploy it. It currently works as-is, but won't run on Heroku unless everything's using the same port.

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);

I'm just learning node as well, so any tips on refactoring in general would be very much appreciated.

Edited to match the suggested solution: (Express works this way, but it breaks 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'));
});

Here's the new error in the console:

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

It looks like websockets are failing so it's falling back to long polling, which is also failing...

Trey Hoover
  • 55
  • 1
  • 5

1 Answers1

10

I think this should work.

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

server.listen(80);

Heroku also has some useful info on the subject: heroku dev info websockets

mauvm
  • 3,586
  • 3
  • 18
  • 19
Niels
  • 1,513
  • 3
  • 20
  • 29