socket.IO- why can't my client html page load socket.io.js?

Problem

My server structure is simple. I have a public folder at the same level as my app.'s

app.js
node_modules(folder)
   express(folder)
   socket.io(folder)
public(folder)
    index.html
    js(folder)
    css(folder)

My app.'s is as follows

var sys         = require('sys'),
        express = require('express'),
        app         = express.createServer('127.0.0.1'),
        io          = require('socket.io');

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
    res.send('Hello World');
});

app.listen(3000);

var socket = io.listen(app);

socket.on('connection', function (client){
  // new client is here!

 });

And my html page(simplified) is

<html>
<p id="text">socket.io</p>


<script src="/socket.io/socket.io.js"></script>
<script type="text/javascript" src="js/lib/jquery-1.4.2.min.js"></script>
</html>

When I run the server and load my index.html, socket.io.js is NOT found, a 404 error is generated. What gives? In my case does socket.IO have to be installed globally?

Problem courtesy of: eco_bach

Solution

Try this:

var sys     = require('sys'),
    express = require('express'),
    app     = express(),
    io      = require('socket.io');

app.use(express.static(__dirname + '/public'));

app.get('/', function (req, res) {
  res.send('Hello World');
});

var server  = app.listen(3000);
var socket  = io.listen(server);

socket.on('connection', function (client){
  // new client is here!
});

Some explanation:

  • express.createServer is deprecated, with Express 3 you run express() to instantiate Express;
  • io.listen should be passed an http.Server instance, whereas you were passing it an Express instance (a http.Server instance is returned by app.listen(...));
  • there's not need to put the socket.io.js file anywhere; socket.io installs a handler which watches for requests for that file, and will serve it automatically;
Solution courtesy of: robertklep

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.