这是真正的长期投票吗? [英] Is this a true long polling?

查看:83
本文介绍了这是真正的长期投票吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

经过大量的尝试,我能够成功地维持服务器与数据库的连续连接. 现在,如果数据库中有新消息,请对keet cheking进行编码并显示消息.

请检查并告知 如果此代码中使用了真正的长轮询技术?然后,请zz建议我在哪里做错了(偏离长轮询),以及如何使它成为真正的长轮询. /p>

Currenlty,我遇到了这些错误.但是它仍然保持着与数据库的连续连接.

  1. 每次,仅拉出一条消息,而不是全部.(我使用.each循环,但它停止了长时间的轮询)
  2. 每10/15秒后,出现令牌错误(解析错误(语法错误=意外令牌)).

    var last_msg_id = 2;
    
    function load_msgs() {
    $.ajax({
    type:"Post",
    url:"getdata.php",
    data:{
        last_msg_id:last_msg_id
    },
    dataType:"json",
    async:true,
    cache:false,
    success:function(data) {
        var json = data;
        $("#commidwin").append(json['msg']);
        last_msg_id = json["last_msg_id_db"];
        setTimeout("load_msgs()", 1000);
    },
    error:function(XMLhttprequest, textstatus, errorthrown) {
        alert("error:" + textstatus + "(" + errorthrown + ")");
        setTimeout("load_msgs()", 15000);
    }
    
    
    
    
    });
    }
    

Php文件在这里

 $last_msg_id=$_POST['last_msg_id'];
$last_msg_id_db=1;

while($last_msg_id>$last_msg_id_db){
    usleep(10000);
    clearstatcache();

    $sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");

    $sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid  FROM chat_com");
    $row_m=mysqli_fetch_array($sql_m);
    $last_msg_id_db=$row_m['maxid'];

    while($row=mysqli_fetch_array($sql)){
        $textt=$row['mesg'];

        $last_msg_id_db=$last_msg_id_db;
        $response=array();
        $response['msg']=$textt;
        $response['last_msg_id_db']=$last_msg_id_db;
    }
}

echo json_encode($response);

解决方案

轮询比一个简单的时间要难一些:仅仅因为一般来说,您输出到浏览器的所有内容都将在完成后进行解释.您的例子很清楚:

success:function(data) {
    var json = data;
    $("#commidwin").append(json['msg']);
    last_msg_id = json["last_msg_id_db"];
    setTimeout("load_msgs()", 1000);
},

jQuery将等待直到响应完成以构建您的data变量,然后将调用您的成功回调.

创建长轮询的一种方法是拥有一个任务和一个关注者:

  • 任务是无限"循环,除了捕获和触发事件外,什么都不显示,仅放在框"中.

  • 跟随者是每X秒进行一次ajax调用,它会在任务填充的框"内显示,并立即在页面内执行操作.

这里是长时间轮询的一个示例,没有追随者,只是一个停止轮询的事件(发布),但是您会明白的:

<?php

// For this demo
if (file_exists('poll.txt') == false)
{
    file_put_contents('poll.txt', '');
}

// If this variable is set, a long-polling is starting...    
if (isset($_GET['poll']))
{

    // Don't forget to change the default time limit
    set_time_limit(120);

    date_default_timezone_set('Europe/Paris');
    $time = time();

    // We loop until you click on the "release" button...
    $poll = true;
    $number_of_tries = 1;
    while ($poll)
    {
        // Here we simulate a request (last mtime of file could be a creation/update_date field on a base)
        clearstatcache();
        $mtime = filemtime('poll.txt');

        if ($mtime > $time)
        {
            $result = htmlentities(file_get_contents('poll.txt'));
            $poll = false;
        }

        // Of course, else your polling will kill your resources!
        $number_of_tries++;
        sleep(1);
    }

    // Outputs result
    echo "Number of tries : {$number_of_tries}<br/>{$result}";
    die();
}

// Here we catch the release form
if (isset($_GET['release']))
{
    $data = '';
    if (isset($_GET['data']))
    {
        $data = $_GET['data'];
    }
    file_put_contents('poll.txt', $data);
    die();
}
?>

<!-- click this button to begin long-polling -->
<input id="poll" type="button" value="Click me to start polling" />

<br/><br/>

Give me some text here :
<br/>
<input id="data" type="text" />
<br/>

<!-- click this button to release long-polling -->
<input id="release" type="button" value="Click me to release polling" disabled="disabled" />

<br/><br/>

Result after releasing polling :
<div id="result"></div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">

    // Script to launch polling
    $('#poll').click(function() {
        $('#poll').attr('disabled', 'disabled');
        $('#release').removeAttr('disabled');
        $.ajax({
            url: 'poll.php',
            data: {
                poll: 'yes' // sets our $_GET['poll']
            },
            success: function(data) {
                $('#result').html(data);
                $('#poll').removeAttr('disabled');
                $('#release').attr('disabled', 'disabled');
            }
        });
    });

    // Script to release polling
    $('#release').click(function() {
        $.ajax({
            url: 'poll.php',
            data: {
                release: 'yes', // sets our $_GET['release']
                data: $('#data').val() // sets our $_GET['data']
            }
        });
    });

</script>

演示:此处.

After lot of trials,I am successfully able to maintain continous server connection with database. Now code keet cheking and show the messages,if there are new in database.

Plz review and tell if there is true long polling technique used in this code? If it is not,then plz suggest,where I am wrong(deviating from long polling) and how this can be made a true long polling.

Currenlty,I am getting these errors.However still it maintains the continous connection with database.

  1. each time,Only one message is pulled instead of all.(I used .each loop but it stops the long polling)
  2. After every 10/15 seconds,token error apperes(Parse erroe(syntax error=unexpected token)).

    var last_msg_id = 2;
    
    function load_msgs() {
    $.ajax({
    type:"Post",
    url:"getdata.php",
    data:{
        last_msg_id:last_msg_id
    },
    dataType:"json",
    async:true,
    cache:false,
    success:function(data) {
        var json = data;
        $("#commidwin").append(json['msg']);
        last_msg_id = json["last_msg_id_db"];
        setTimeout("load_msgs()", 1000);
    },
    error:function(XMLhttprequest, textstatus, errorthrown) {
        alert("error:" + textstatus + "(" + errorthrown + ")");
        setTimeout("load_msgs()", 15000);
    }
    
    
    
    
    });
    }
    

Php file is here

 $last_msg_id=$_POST['last_msg_id'];
$last_msg_id_db=1;

while($last_msg_id>$last_msg_id_db){
    usleep(10000);
    clearstatcache();

    $sql=mysqli_query($db3->connection,"SELECT * FROM chat_com where id>'$last_msg_id' ORDER by id ASC");

    $sql_m=mysqli_query($db3->connection,"SELECT max(id) as maxid  FROM chat_com");
    $row_m=mysqli_fetch_array($sql_m);
    $last_msg_id_db=$row_m['maxid'];

    while($row=mysqli_fetch_array($sql)){
        $textt=$row['mesg'];

        $last_msg_id_db=$last_msg_id_db;
        $response=array();
        $response['msg']=$textt;
        $response['last_msg_id_db']=$last_msg_id_db;
    }
}

echo json_encode($response);

解决方案

Polling is a bit harder than a simple while : just because generally all things you output to the browser will be interpreted when complete. Your example is quite clear :

success:function(data) {
    var json = data;
    $("#commidwin").append(json['msg']);
    last_msg_id = json["last_msg_id_db"];
    setTimeout("load_msgs()", 1000);
},

jQuery will wait until the response is complete to build your data variable and then will call your success callback.

One way to create long-polling is to have a task and a follower :

  • the task is the "infinite" loop, it displays nothing but just catch and trigger events, put in a "box".

  • the follower is an ajax call made every X seconds, it looks inside the "box" filled by the task, and immediately act inside the page.

Here is an example of long-polling, there is no follower, just an event (release) that stops the poll, but you'll get the idea :

<?php

// For this demo
if (file_exists('poll.txt') == false)
{
    file_put_contents('poll.txt', '');
}

// If this variable is set, a long-polling is starting...    
if (isset($_GET['poll']))
{

    // Don't forget to change the default time limit
    set_time_limit(120);

    date_default_timezone_set('Europe/Paris');
    $time = time();

    // We loop until you click on the "release" button...
    $poll = true;
    $number_of_tries = 1;
    while ($poll)
    {
        // Here we simulate a request (last mtime of file could be a creation/update_date field on a base)
        clearstatcache();
        $mtime = filemtime('poll.txt');

        if ($mtime > $time)
        {
            $result = htmlentities(file_get_contents('poll.txt'));
            $poll = false;
        }

        // Of course, else your polling will kill your resources!
        $number_of_tries++;
        sleep(1);
    }

    // Outputs result
    echo "Number of tries : {$number_of_tries}<br/>{$result}";
    die();
}

// Here we catch the release form
if (isset($_GET['release']))
{
    $data = '';
    if (isset($_GET['data']))
    {
        $data = $_GET['data'];
    }
    file_put_contents('poll.txt', $data);
    die();
}
?>

<!-- click this button to begin long-polling -->
<input id="poll" type="button" value="Click me to start polling" />

<br/><br/>

Give me some text here :
<br/>
<input id="data" type="text" />
<br/>

<!-- click this button to release long-polling -->
<input id="release" type="button" value="Click me to release polling" disabled="disabled" />

<br/><br/>

Result after releasing polling :
<div id="result"></div>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">

    // Script to launch polling
    $('#poll').click(function() {
        $('#poll').attr('disabled', 'disabled');
        $('#release').removeAttr('disabled');
        $.ajax({
            url: 'poll.php',
            data: {
                poll: 'yes' // sets our $_GET['poll']
            },
            success: function(data) {
                $('#result').html(data);
                $('#poll').removeAttr('disabled');
                $('#release').attr('disabled', 'disabled');
            }
        });
    });

    // Script to release polling
    $('#release').click(function() {
        $.ajax({
            url: 'poll.php',
            data: {
                release: 'yes', // sets our $_GET['release']
                data: $('#data').val() // sets our $_GET['data']
            }
        });
    });

</script>

Demonstration : here.

这篇关于这是真正的长期投票吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆