0

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!

Evercx
  • 3
  • 1
  • 3

2 Answers2

3

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

jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Great! I replaced app.listen() with server.listen() and thus client find socket.io/socket.io.js. I make it. Thank you very much! – Evercx Mar 21 '16 at 10:34
0

You need use the below line of code in app.js after the line app.use(express.static('public'));

  app.use("/lib", express.static(path.join(__dirname,'node_modules'))); 

and then import in your client as below

   <script src='/lib/socket.io/socket.io.js' type='text/javascript'></script>
Nalla Srinivas
  • 913
  • 1
  • 9
  • 17