Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Socket.io and Express3 - 404 on client request to /socket.io/socket.io.js

I am receiving a 404 when trying to resolve '/socket.io/socket.io.js' from my Node server. I can't determine why.

My server configuration looks like this:

 var express = require('express')
  , engine = require('ejs-locals')
  , app = express()
  , http = require('http')
  , server = http.createServer(app)
  , io = require('socket.io').listen(server);


// use ejs-locals for all ejs templates:
app.engine('ejs', engine);

app.set('views',__dirname + '/views');
app.set('view engine', 'ejs'); // so you can render('index')
app.use(express.static(__dirname + '/public'));

//define routes
...

app.listen(3000);



//socket io
io.sockets.on('connection', function (socket) {
  socket.on('set nickname', function (name) {
    socket.set('nickname', name, function () {
      socket.emit('ready');
    });
  });

  socket.on('msg', function () {
    socket.get('nickname', function (err, name) {
      console.log('Chat message by ', name);
    });
  });
});  

At the client I have this:

<script src="/socket.io/socket.io.js"></script>
<script>
  var socket = io.connect('http://localhost:3000');
  socket.on('news', function (data) {
    console.log(data);
    socket.emit('my other event', { my: 'data' });
  });
</script>

I am testing this locally (port: 3000). The Socket code is basically ripped off of the socket.io example to get something working. I have reviewed other posts and can't seem to find where I'm going wrong. Can someone help?

Thanks

like image 647
Nick Avatar asked Mar 24 '23 20:03

Nick


1 Answers

Got it!

The HTTP server needs to be listing on the port (3000 in this case.) I then removed the app.listen(3000) as the address will already be in use and is not needed.

Thanks!

var express = require('express')
  , engine = require('ejs-locals')
  , app = express()
  , http = require('http')
  , server = http.createServer(app).listen(3000)
  , io = require('socket.io').listen(server);
like image 98
Nick Avatar answered Apr 06 '23 10:04

Nick