jvjefke
jvjefke

Reputation: 21

Socket.io not working with Express 4 without using diffrent port number

My application works when i specify a port number to socket.io that is diffrent from the server port number. The working code goes as follows:

This is my app.js file:

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 mongoose = require('mongoose');
var configDB = require('./config/database.js');
var session = require('express-session');
var passport = require('passport');

var routes = require('./routes/index');
var auth = require('./routes/auth.js');

var app = express();

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

// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.set(process.env.PORT || 1337);
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(require('stylus').middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));
app.use(session({ secret: 'mysessionsecret' }));
app.use(passport.initialize());
app.use(passport.session());

mongoose.connect(configDB.url);

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

// 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: {}
    });
});

var talk = require('./socket/talk.js')(app);

module.exports = app;

This is my talk.js file:

var init = function (app){    
    var server = require("http").createServer(app).listen(3000);
    var io = require("socket.io").listen(server);

    var socketioJwt = require("socketio-jwt");
    var jwtSecret = require('../config/jwtSecret');

    console.log("init");

    io.set("authorization", socketioJwt.authorize({
        secret: jwtSecret,
        handshake: true
    }));

    io.sockets.on("connection", function (socket) {
        console.log("connected");
        socket.on("send", function (data) {
            console.log(data);
            var username = data.username;
            var message = data.message;
            var datetime = data.datetime;

            socket.broadcast.emit("send", data);
        });
        socket.on("busy", function () {
            socket.emit("busy");
            socket.broadcast.emit("busy");
        });
        socket.on("free", function () {
            socket.emit("free");
            socket.broadcast.emit("free");
        });
    });
}

module.exports = init;

This is my script tag in index.ejs:

<script src="http://localhost:3000/socket.io/socket.io.js"></script>

And finally this is my io connect from the client:

socket = io("http://localhost:3000/",{
            query: 'token=' + tok
        });

This works but the problem is that i want to publish my site to Azure but it is not possible to let a Azure website listen to diffrent ports. At least i think it is not possible.

One of the many things I tried is changing the talk.js file to this:

var init = function (app){    
    var server = require("http").createServer(app).listen(app.get('port'));
    var io = require("socket.io").listen(server);
...

But i it doesn't work. I always get something along the lines of http://localhost/socket.io/socket.io.js not found

If i change the script tag in my index.ejs file to this

<script src="http://cdn.socket.io/socket.io-1.2.1.js"></script>

The socket.io.js file gets loaded but when i connect form te client side i get a continious 404 not found error.

I looked at a lot of solutions online but none of them work. I really don't know what i am doing wrong.

Upvotes: 2

Views: 2203

Answers (1)

Harijoe
Harijoe

Reputation: 1791

This error comes from the bin/www.js file being called before app.js when using npm start. A quick solution is to bypass www.js, which is only used to handle some common errors, as it is suggested in this answer.

This github repo is an implementation of this solution and can be used as a starting point for any Express.js + socket.io application.

Upvotes: 1

Related Questions