Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
932 views
in Technique[技术] by (71.8m points)

node.js - socket.io: Failed to load resource

I'm trying to getting started with socket.io and node.js.

Following the first example on the socket.io's site I'm getting the following error in the browser's console:

Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:3001/socket.io/socket.io.js
Uncaught ReferenceError: io is not defined 

This is my server.js

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

app.listen(3001);

app.get('/', function (req, res) {
  res.sendfile(__dirname + '/index.html');
});

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

And this is my index.html

<!DOCTYPE html>
<html>
  <head>
    <title></title>
    <meta charset="UTF-8" />
  </head>
  <body>
    <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>
  </body>
</html>

I've already installed socket.io..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The Issues

  • First of all you need to be looking at the server port that the server is bound on (app.listen(3001);) on the client side in order to reach the server at all.

  • As for socket.io, adding http://localhost:3001 before the rest of the source in the link tag solves this problem. This is apparently due to the way the network binds ports to localhost, however I will try to find some more information on the cause;

What to change:


The port binding for the server:

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

should be change to

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



Making socket.io behave:

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

should be change to

<script src="http://localhost:3001/socket.io/socket.io.js"></script>



与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...