Search code examples
node.jssocket.ioexpress-4

socket.io is not found with Express 4?


I have been trying to get my client connected with my server,but chrome always print that

GET http://localhost:30653/socket.io/socket.io.js 404 (Not Found)

I don't know where's the problem...

the express version is "4.13.4" and socket.io version is "1.4.5"

And here is my code:

app.js

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

io.on('connection',function(socket){
    console.log("connected");
    socket.emit('open');
});

app.set('port', process.env.PORT || 30653);
app.set('view engine','html');
app.engine('html',hbs.__express);
app.use(express.static('public'));
app.get('/',function(req,res){
    res.render('chatroom');
});
app.listen(app.get('port'),function(){
    console.log('this server is listening on port:'+app.get('port'));
});

client:

$(function(){
    var socket = io.connect('http://localhost:30653');
    socket.on('open',function(){
        console.log("open")
    });
    socket.on('system',function(json){
        console.log("system");
    });
});

any help is welcome!I'll be very appreciate it!


Solution

  • I think your app.listen(...) needs to be server.listen(...) because of the way you are creating your server as illustrated here: http://socket.io/docs/#using-with-express-3/4. The way you are doing it, socket.io is not hooked to the right server and thus is not serving the socket.io.js file for you.

    You can do app.listen(), but only if you follow a different initialization procedure here: http://socket.io/docs/#using-with-the-express-framework