1

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?

3
  • 1
    Does socket.io.js exist in the folder /public/socket.io/ ? Commented Dec 6, 2013 at 19:11
  • Two things. (1) What happens if you remove the leading / from "/socket.io/socket.io". (2) I've got a working example described in this answer that might help you: stackoverflow.com/a/20426209/446681 Commented Dec 6, 2013 at 19:19
  • 1
    One more thing, file socket.io.js does not have to be in the public folder. This request is automatically processed by socket.io on the server as indicated in this other answer: stackoverflow.com/a/19521970/446681 Commented Dec 6, 2013 at 19:27

1 Answer 1

6

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;
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.