减少AJAX请求大小.与Polling系统简单聊天

tom*_*rod 9 javascript php jquery xmlhttprequest ajax-polling

注意: 我更换了我的投票系统,websockets我仍然想知道上述问题的答案.

我正在尝试减少传统轮询消息系统的AJAX请求,但我不知道如何获取它:

$chatbox = $("#chatbox");

setInterval(function(){
    // I send the sha1 of the chatbox html content to verify changes.
    $.post("post.php", {checksum: hex_sha1($chatbox.html())}, function (data, status) {

        switch (status) {
            case "success": 
                // If version of "post.php" checksum is different than mine (there are changes) data isn't empty; I assign data as the new content of the chatbox.
                if(data){ 
                    $chatbox.html(data);      
                    $chatbox.scrollTop($chatbox[0].scrollHeight); 
                } 
            break;

            default: 
                $chatbox.html('Connection error...'); 
            break;                       
        }                       
    });
}, 1000);
Run Code Online (Sandbox Code Playgroud)

好吧,如你所见,我使用setInterval()with 1000miliseconds作为参数,并且由于SHA1校验和系统,我可以减少所有AJAX响应的大小343 B(除非"post.php"返回一些新消息,显然)


问题:

  • 为什么我的所有AJAX请求都具有相同的大小(343 B)即使我将SHA1(20 B)哈希更改为MD5(16 B)?

  • 我的校验和变量(SHA1)占用20 B:其余的在哪里 323 B

  • 我可以减少更多的AJAX请求大小吗? 怎么样?


注意:

hex_sha1()是Javascript 的SHA1算法的实现:http: //pajhome.org.uk/crypt/md5/sha1.html

笔记2:

不幸的是,我不能使用像服务器推送技术node.js.我只能使用Javascript(客户端)和PHP.

Gia*_*año 1

为什么不使用普通的 javascript AJAX 请求?也许你的AJAX数据太长了,这就是为什么它有很大的尺寸:而你唯一能做的就是让AJAX数据有一些数据。

你想要什么?喜欢 Facebook AJAX 轮询?在服务器 PHP 上这样做:

$chat_data = "(this is the chat data variable if there is no chat data it will idle)";
while (!$chat_data) {
     // when there's no chat data let's idle the request without disconnecting
     // the client from the AJAX request.
     sleep(1);
}
exit(json_encode($chat_data));
Run Code Online (Sandbox Code Playgroud)

在 JavaScript 客户端:

function repoll () {
     chat_poll = new XMLHttpRequest();
     // the chat_req variable is for sending POST data to the server.
     chat_req = new FormData();
     chat_req.append("do", "chatpoll");
     chat_poll.open("POST", "post.php");
     chat_poll.send(chat_req);
     chat_poll.onload = function () {
     // do something here with the chat data
     // repoll the server
     repoll();
}

repoll();
Run Code Online (Sandbox Code Playgroud)

通过这样做,您可以实现类似 Facebook 的服务器轮询。


websocket以JavaScript 客户端为例:

web_socket = new WebSocket("ws://[thesocket]:[theport]");
web_socket.onmessage = function (w) {
     // do something here. this will fire if messages is received from the websocket.
     // you will get the message from w.data variable.
     alert("Data Received: " + w.data);
}

// to send data to the web socket do this:
web_socket.send("the data you want. I prefer JSON for sending configuration and chat data or XML if you want");
Run Code Online (Sandbox Code Playgroud)