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[pathname] === "function"){
    	handle[pathname](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);
        }
    });
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值