nodejs实现long-polling
运行方式如下:node long.js
不断往服务器目录放置message文件如:(echo "new message" > message)
首页index.html如下
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Test Long-Polling</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<div id="container">
<h1>Test Long-Polling</h1>
<ul id="results">
</ul>
</div>
<script>
$(function ($) {
function longPoll() {
$.ajax({
type: 'POST',
url: 'http://127.0.0.1:8080/get',
data: '',
success: function(data) {
console.log(data);
$('#results').append('<li>' + data + '</li>');
longPoll(); //获取到数据后继续发起请求
},
error:function(){
setTimeout(function(){ //如果网络或者服务器异常,则等待5s再发起请求
longPoll();
}, 5000);
}
});
}
longPoll();
});
</script>
</body>
</html>
服务long.js如下:
var http = require("http"),
url= require("url"),
path = require("path"),
fs = require("fs");
var handle = {}
handle["/get"] = getHandler;
var handleStream;
http.createServer(function (req, res) {
var pathname=url.parse(req.url).pathname;
if(typeof handle === "function"){
handle(res, req);
}
else {
/*
* 发送静态页面:首页
*/
pathname=__dirname+url.parse(req.url).pathname;
if (path.extname(pathname)=="") {
pathname+="/";
}
if (pathname.charAt(pathname.length-1)=="/"){
pathname+="index.html";
}
fs.exists(pathname,function(exists){
if(exists){
switch(path.extname(pathname)){
case ".html":
res.writeHead(200, {"Content-Type": "text/html"});
break;
default:
res.writeHead(200, {"Content-Type": "application/octet-stream"});
}
fs.readFile(pathname,function (err,data){
res.end(data);
});
} else {
res.writeHead(404, '404 Not Found', {'Content-Type': 'text/html'});
res.end('<h1>404 Not Found</h1>');
}
});
}
}).listen(8080, "0.0.0.0");
console.log("Server running at http://0.0.0.0:8080/");
function getHandler(res, req){//如果是post方式请求,返回消息,否则返回404,简单的安全保证
if (req.method == 'POST') {
return handleStream(req, res);
}
res.writeHead(404, '404 Not Found', {'Content-Type': 'text/html'});
res.end('<h1>404 Not Found</h1>');
}
//用文本文件模拟消息或者数据库,正式环境还是应该用mysql或者redis替换
handleStream = function (req, res) {
var filename = './message';
fs.readFile(filename, 'utf8', function (err, data) {
if (!err) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end(data);
fs.unlinkSync(filename) //删掉message文件
} else {
//设置10秒以后重新检测message文件内容
setTimeout(function() { handleStream(req, res) }, 10000);
}
});
}
页:
[1]