缺少socket.io.js

时间:2013-01-05 00:23:40

标签: node.js express socket.io

启动app.js时我得到了

$ node app.js info:socket.io开始

然而,运行index.html它说它缺少

 GET http://localhost:3000/socket.io/socket.io.js 404 (Not Found) localhost:5
 Uncaught ReferenceError: io is not defined 

我使用了npm install socket.io express

app.js

 var express = require('express')
   , http = require('http');

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

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

 app.configure(function(){
   app.set('port', process.env.PORT || 3000);
   app.use(express.bodyParser());
 });

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

的index.html

 <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>

1 个答案:

答案 0 :(得分:3)

你的代码看起来有些混乱。通过改变它来实现它:

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

app.configure(function(){
  app.use(express.bodyParser());
});

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

server.listen(process.env.PORT || 3000);