试验一篇教程上的例子,得不到应有的效果。
发布于 2年前 作者 mozatt 1010 次浏览

我是新手。最近下载了Mixus Node Book这篇pdf文档。试着执行文档内的例程。在试验Simple Messaging application一节的例子时,遇到了问题。发出来请高手帮看看。 这是一个简单的消息推送服务器。发布消息使用:http://192.168.77.159:7778/msg/这里是消息内容。页面获取消息采用jQuery的long polling方式。在一台CentOS虚拟机下测试,用这台虚拟机的FireFox访问。

服务端代码: var http = require(‘http’), url = require(‘url’), fs = require(‘fs’); var messages = [“testing”]; var clients = [];

http.createServer(function(req, res) { var url_parts = url.parse(req.url); console.log(url_parts); if ( url_parts.pathname.substr(0, 5) == ‘/poll’ ) { console.log(‘request /poll’); var count = url_parts.pathname.replace(/[^0-9]*/, ‘’); console.log(count); if ( messages.length > count ) { console.log(‘send response’); res.end(JSON.stringify({ count:messages.length, append:messages.slice(count).join(“\n”)+"\n" })); } else { console.log(‘appending the client’); clients.push(res); } } else if ( url_parts.pathname.substr(0, 5) == ‘/msg/’ ) { console.log(‘request /msg/’); var msg = unescape(url_parts.pathname.substr(5)); console.log(msg); messages.push(msg); while ( clients.length > 0 ) { var client = clients.pop(); client.end(JSON.stringify({ count:messages.length, append:msg+"\n"})); } res.end(); } }).listen(7778, ‘192.168.77.159’); console.log(‘Server running.’);

客户端发送消息不需要编写代码,在浏览器的地址栏内直接输入url外加消息内容即可。 这是消息获取页面客户端代码: <html> <head> <script src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <script> var counter = 0; var poll = function() { $.getJSON('http://192.168.77.159:7778/poll/’+counter, function(response){ alert(“dsf”); counter = response.count; var elem=$(‘#output’); elem.text(elem.text() + response.append); poll(); }); } poll(); </script> </head>

<body> <textarea id="output" style="width:100%; height:100%;"> </textarea> </body>w </html>

现在遇到的问题是,获取消息的页面始终无法显示出任何消息内容。但如果在浏览器的地址栏内直接输入这样的地址,就能看到json格式字串:http://192.168.77.159:7778/poll/0

我曾试着将客户端代码换成手写的ajax调用代码,不知为何req.status的值却是0。还望高手指点一二!

3 回复

这是客户端页面代码,因为不知道怎么发布代码,所以在尖括号处多加了个横杠符。

<-html> <-head> <-script src="http://code.jquery.com/jquery-1.6.4.min.js"></script> <-script> var counter = 0; var poll = function() { $.getJSON('http://192.168.77.159:7778/poll/’+counter, function(response){ alert(“dsf”); counter = response.count; var elem=$(‘#output’); elem.text(elem.text() + response.append); poll(); }); } poll(); <-/script> <-/head> <-body> <-textarea id="output" style="width:100%; height:100%;"> <-/textarea> <-/body> <-/html>

调用这个客户端页面的方式就是在浏览器内直接访问这个地址:file:///root/Desktop/a.html。

希望高手看到给点提示啊,多谢了!

回到顶部