Socket.IO简单快速示例不适用于OS X Mountain Lion

时间:2012-08-13 03:44:58

标签: node.js express socket.io

我正在使用https://github.com/LearnBoost/socket.io中的以下示例代码来启动Socket.IO和Express示例。

当我到localhost时,我收到此错误:

Cannot GET /

我的app.js看起来像这样:

var express = require('express');
var io = require('socket.io');
var server = require('http');

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

server.listen(80);

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>

的软件包:

npm ls
├─┬ express@3.0.0rc2
│ ├── commander@0.6.1
│ ├─┬ connect@2.4.2
│ │ ├── bytes@0.1.0
│ │ ├── formidable@1.0.11
│ │ ├── pause@0.0.1
│ │ └── qs@0.4.2
│ ├── cookie@0.0.4
│ ├── crc@0.2.0
│ ├── debug@0.7.0
│ ├── fresh@0.1.0
│ ├── methods@0.0.1
│ ├── mkdirp@0.3.3
│ ├── range-parser@0.0.4
│ └─┬ send@0.0.3
│   └── mime@1.2.6
└─┬ socket.io@0.9.10
  ├── policyfile@0.0.4
  ├─┬ redis@0.7.2
  │ └── hiredis@0.1.14
  └─┬ socket.io-client@0.9.10
    ├─┬ active-x-obfuscator@0.0.1
    │ └── zeparser@0.0.5
    ├── uglify-js@1.2.5
    ├─┬ ws@0.4.21
    │ ├── commander@0.6.1
    │ ├── options@0.0.3
    │ └── tinycolor@0.0.1
    └── xmlhttprequest@1.4.2

谢谢!

1 个答案:

答案 0 :(得分:2)

您没有指示Express为您的index.html文件提供服务。运行它的最简单方法可能就是创建一个名为public的目录并将index.html放入其中,然后修改Express服务器,使其从该目录中提供静态文件:

var express = require('express');
var io = require('socket.io');
var server = require('http');
var path = require('path');

var app = express()
  , server = require('http').createServer(app)
  , io = io.listen(server);
app.use(express.static(path.join(__dirname, 'public')));

然后在浏览器中访问localhost/index.html