Show toolbar

2013年7月18日 星期四

Data Synchronization Update

標題:同步變更數據
Node.JS (getdata.js):
var server,
    ip   = "127.0.0.1",
    port = 1337,
    http = require("http"),
    url = require("url"),
    fs = require("fs"),
    qs = require("querystring");

var textPath = "p.txt";

server = http.createServer(function (req, res) {
    var polling = {
        timeover : false,
        timeout : null,
        request : function(q) {
            this.timeout = setTimeout(function() {
                polling.timeover = true;
            }, 10000);
            this.action(q);
        },
        action : function(q) {
            if(this.timeover == true) { //確認連線逾時
                q.callback({});
            } else {
                fs.readFile(textPath, "utf-8", function(err, file) {
                    if(q.json.lastTime < qs.parse(file).lastTime) { //有新資料
                        q.callback(qs.parse(file));
                    } else { //駐列輪巡
                        setTimeout(function() { polling.action(q) }, 100);
                    }
                });
            }
        }
    };
    
    switch(url.parse(req.url).pathname) {
        case "/jquery":
            fs.readFile("js/jquery-1.9.1.js", function (err, data) {
                if(err) throw err;
                res.writeHead(200, {"Content-Type": "text/javascript", "Content-Length":data.length});
                res.write(data);
                res.end();
            });
            break;
        case "/index":
            fs.readFile("index.html", function (err, data) {
                if(err) throw err;
                res.writeHead(200, {"Content-Type": "text/html", "Content-Length":data.length});
                res.write(data);
                res.end();
            });
            break;
        case "/sendData":
            var sendData = "";
            var lastTime = new Date().getTime();
            req.setEncoding("utf8");
            req.addListener("data", function(sendDataChunk) {
                sendData += sendDataChunk;
            });
            req.addListener("end", function() {
                sendData += "&lastTime=" + lastTime;
                fs.open(textPath, "w", 0644, function(err, fd) {
                    if(err) throw err;
                    fs.write(fd, sendData, 0, "utf8", function(err) {
                        if(err) throw err;
                        fs.closeSync(fd);
                        var json = JSON.stringify({lastTime: lastTime});
                        res.writeHead(200, {
                            "Content-Type": "text/json",
                            "Content-Length": json.length
                        });
                        console.log(json);
                        res.end(json);
                    })
                });
            });
            break;
        case "/getData":
            var getData = "";
            req.setEncoding("utf8");
            req.addListener("data", function(getDataChunk) {
                getData += getDataChunk;
            });
            req.addListener("end", function() {
                polling.request({
                    json : qs.parse(getData),
                    callback : function(data) {
                        var json = JSON.stringify(data);
                        res.writeHead(200, {
                            "Content-Type": "text/json",
                            "Content-Length": json.length
                        });
                        res.end(json);
                    }
                });
            });
            break;
        default:
            res.writeHead(200, {"Content-Type": "text/html"});
            res.write("Page not found.");
            res.end();
            break;
    }
    
});

server.listen(port);

console.log("Server running at http://" + ip + ":" + port);
HTML (index.html):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-TW" xml:lang="zh-TW">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Title</title>
<script src="/jquery"></script>
<script type="text/javascript">
$(function() {
    var localurl = window.location.protocol + "//" + window.location.host;
    var lastTime = 0;
    $("#sendBtn").click(function() {
        var username = $("#username").val();
        var xValue = $("#xValue").val();
        var yValue = $("#yValue").val();
        var zValue = $("#zValue").val();
        $.post("/sendData", {user: username, x: xValue, y: yValue, z: zValue},
        function(data) {
            console.log("Message Send on " + data.lastTime);
        }, "json");
    });
    var pollingData = function() {
        $.ajax({
            cache: false,
            dataType: "json",
            type: "POST",
            url: localurl + "/getData",
            data: {lastTime: lastTime},
            error: function (xhr, status, error) {
                document.write("Error");
            },
            success: function (json) {
                //console.log(json);
                if(!$.isEmptyObject(json)) { //判斷內容是否為空
                    console.log("Update...");
                    //lastTime = new Date().getTime();
                    $("#username").val(json.user);
                    $("#xValue").val(json.x);
                    $("#yValue").val(json.y);
                    $("#zValue").val(json.z);
                    lastTime = json.lastTime;
                    pollingData();
                } else { //繼續輪巡
                    console.log("Pulling...");
                    pollingData();
                }
            }
        });
    };
    pollingData();
});
</script>
</head>
<body>
name: <input type="text" id="username" value="QQBoxy" /><br />
x: <input type="text" id="xValue" value="3" /><br />
y: <input type="text" id="yValue" value="4" /><br />
z: <input type="text" id="zValue" value="5" /><br />
<button id="sendBtn">Send</button>
</body>
</html>
Batch (Start.bat):

說明:
使用Node.JS與jQuery進行數據同步變更。

沒有留言:

張貼留言