2

Over the weekend, I was trying to figure out websockets (since I think it would probably be a really fun thing to know).

I did a search around for socket.io tutorials and found this Good beginners tutorial to socket.io? which suggested I start on http://socket.io

On a fresh ubuntu I built node.js 4.1.13-pre (many packages won't work with the current 0.5.8)

I added, NPM and the express, jade & socket.io packages.

I set up and ran a server:

var io = require('socket.io').listen(8000);  // I moved the port
var express = require('express');  // I had to add this
io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
    console.log(data);
  });
});

I cloned https://github.com/LearnBoost/socket.io.git and made an index.html in the directory above the place I cloned socket IO into

 <script src="socket.io/lib/socket.io.js"></script> <!-- changed path from example -->
 <script>
   var socket = io.connect('http://localhost:8000');
   socket.on('news', function (data) {
     console.log(data);
     socket.emit('my other event', { my: 'data' });
   });
 </script>

When I load up the index page locally, I get the error: require not defined

I'm assuming that I've missed something here, is the client-side JS not the same one from the lib folder? DO I need to add something to allow for the existence of 'require'?

What am I missing? How do I serve up the client side JS correctly?

Community
  • 1
  • 1
Alex C
  • 16,624
  • 18
  • 66
  • 98

1 Answers1

4

Try <script src="/socket.io/socket.io.js"></script> instead.

Daniel Brockman
  • 18,826
  • 3
  • 29
  • 40
  • I should probably have mentioned that the reason I switched from the "documentation-provided" code was because that didn't work either. What I *didn't* try is `"http://localhost:8000/socket.io/socket.io.js"` maybe socket.io 'compiles' and server the client-code and adds its own url-transport to express. – Alex C Sep 26 '11 at 15:08
  • 1
    Yes, Socket.IO takes care of serving the client code. But `/socket.io/socket.io.js` should be equivalent to `http://localhost:8000/socket.io/socket.io.js` (assuming you are serving the HTML file from `http://localhost:8000`). – Daniel Brockman Sep 26 '11 at 15:15
  • Thanks, I knew it was something simple. I'm definitely going to want to communication / socket server to be separate from the static files. So I guess I was trying to run before I could walk. The static page was being served seperately, which complicated stuff. – Alex C Sep 26 '11 at 15:58
  • 1
    Tested and verified - you actually serve the client side JS file *through* the socket itself. So, if you're socket is on 8000 you pull the client side JS through `http://localhost:8000/socket.io/socket.io.js` not the express default `3000` or whatever. – Alex C Sep 26 '11 at 18:59
  • Thank you, stuck on that for ages! – Richard Dalton Feb 15 '12 at 22:36