0
votes

I am trying to create an Express app with Socket.IO. It seems like Express has changed quite a lot and most of the code online about getting the 2 to work together is out of date. This is what I have:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

var app = express();

var http = require('http').Server(app);
var io = require('socket.io').listen(http);
io.on('connection', function(socket){
    console.log('a user connected');
});

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/users', users);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

// error handlers

// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
    res.status(err.status || 500);
    res.render('error', {
        message: err.message,
        error: {}
    });
});

module.exports = app;

The server starts ok and says

info - socket.io started

However the front-end has a 404 error on http://example.com:3000/socket.io/socket.io.js

edit

If I add

http.listen(8080);

The server runs twice on port 3000 and 8080, the 3000 version does not load socket.io.js and the 8080 version does. How can I have it so the server is only running on 3000? changing it to 3000 errors and it tries to listen twice

2

2 Answers

2
votes

The answer was to make the changes in bin/www.js instead of app.js

#!/usr/bin/env node
var debug = require('debug')('test1');
var app = require('../app');

app.set('port', process.env.PORT || 3000);

var http = require('http').Server(app);
var io = require('socket.io')(http);

var server = http.listen(app.get('port'), function() {
  debug('Express server listening on port ' + server.address().port);
});
1
votes

Change the io include to:

var io = require('socket.io')(http);

And towards the bottom add something like:

http.listen(3000, function() {
  console.log('Listening on port %d', http.address().port);
});