本地主机不适用于 node.js 和 socket.io

Localhost not working with node.js and socket.io

我正在尝试学习 node.js 和 socket.io 的基础知识。我一直在使用这个教程http://tutorialzine.com/2012/08/nodejs-drawing-game/

这个问题的完整代码可以在上面的link中看到。

我可以使用 node.js 创建一个基本的 Web 服务器并将其发送到 return hello world 所以我确信它安装正确。但是在安装这些包后

npm install socket.io@0.9.10 node-static

并按照说明设置服务器端 js

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
nstatic = require('node-static');

var fileServer = new nstatic.Server('./');

app.listen(8080);

我只是在我的 cmd 和一个不断挂起的 Web 浏览器中得到这个提示,而不是 html 页面,served.I 认为我可能搞砸了安装,但在查看在 npm 中安装的软件包列表中,它指出 socket.io 和 node-static 都存在。

下面的代码应该更有效?,您似乎缺少处理程序部分。响应必须明确结束,否则浏览器请求将像您所看到的那样永远挂起。 node-static file.serve 方法在您传递请求后对其进行管理。 .serve 的来源在这里:https://github.com/cloudhead/node-static/blob/master/lib/node-static.js#L164

var app = require('http').createServer(handler),
io = require('socket.io').listen(app),
nstatic = require('node-static');

app.listen(8080);
var file = new nstatic.Server('./');

function handler(request, response) {
    request.addListener('end', function () {
        file.serve(request, response);
    }).resume();
}

console.log('started')

另请注意,用于响应 / 的默认文件是 index.html