Localhost不使用node.js和socket.io

时间:2016-01-02 15:20:31

标签: node.js socket.io

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

此问题的完整代码可以在上面的链接中看到。

我可以使用node.js创建一个基本的Web服务器并让它返回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页面。我想我可能搞砸了安装,但是看了npm中安装的软件包列表它表示存在socket.io和node-static。

enter image description here

1 个答案:

答案 0 :(得分:1)

下面的代码应该更有效吗?看起来你错过了处理程序部分。必须明确结束响应,否则浏览器请求会像您看到的那样永远挂起。一旦传递了请求,node-static index方法就会管理该请求。 file.serve的来源位于:https://github.com/cloudhead/node-static/blob/master/lib/node-static.js#L164

.serve

另请注意,用于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') 的回复的默认文件为/