nodejs実現long-polling

4180 ワード

運転方式は以下の通りです.
node long.js
常にサーバディレクトリにメッセージファイルを置きます.
トップページのindex.
<!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);
        }
    });
}