0
votes

I have index.html as such:

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

app.js as such:

var app = require('http').createServer(handler)
  , io = require('socket.io').listen(app)
  , fs = require('fs')

app.listen(80);

function handler (req, res) {
  fs.readFile(__dirname + '/index.html',
  function (err, data) {
if (err) {
  res.writeHead(500);
  return res.end('Error loading index.html');
}

res.writeHead(200);
res.end(data);
  });
}

io.sockets.on('connection', function (socket) {
  socket.emit('news', { hello: 'world' });
  socket.on('my other event', function (data) {
console.log(data);
  });
});

These files are placed within /var/www.

I ran:

sudo npm install socket.io

so, now I have a folder: /var/www/node_modules/socket.io

Within my browser (chrome), I typed 'localhost' - I got a file not found error (in chrome's console) for socket.io.js. So within index.html, I modified the src line to:

<script src="node_modules/socket.io/lib/socket.io.js"></script>

But then I got a file not found error elsewhere (within socket.io.js):
Uncaught ReferenceError: require is not defined

for the following line:

var client = require('socket.io-client');

Do I just keep changing the paths to all these files?
I also get an 'io is not defined' error at index.html at the following line:

var socket = io.connect('http://localhost');

Server side
When I go into the terminal and type

node app.js

I get the following error:
info - socket.io started
warn - error raised: Error: listen EACCES

Please, help. Thank you.

1

1 Answers

0
votes

I solved the server side problem by changing the port number (as 80 was already in use) to 8000 in my case.

I then ran app.js via the terminal & left it running.

I typed

http://localhost:8000/index.html 

into my web browser and it all works fine.

I even used:

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

in index.html. If you get the server running first, the browser is able to find paths to all the right nodejs files.