Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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...

like image 890
Trey Hoover Avatar asked Feb 25 '15 21:02

Trey Hoover


1 Answers

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

like image 161
Niels Avatar answered Oct 10 '22 04:10

Niels