AJAX长轮询在一分钟不活动后关闭

时间:2014-02-23 15:07:30

标签: php mysql ajax

我正在尝试构建聊天应用程序,我决定继续长时间的投票。无论如何,如果用户处于活动状态,则消息正在显示,但如果我尝试在一分钟后发送消息,则在刷新之前没有任何反应。如何保持连接打开?这是代码:

index.php
<table style="width: 100%;">
    <tbody>
        <tr>
            <td width="50%">
                <h4>Received Messages (Live Stream)</h4>
                <ul class="items">
                <?php 
                $result = mysql_query("SELECT * FROM messages ORDER BY ID DESC");
                $num_rows = mysql_num_rows($result);
                if( $num_rows >= 1):
                while ($row = mysql_fetch_array($result, MYSQL_ASSOC)):
                ?>
                    <li><?php echo $row['ID'] . '. ' . $row['msg_text']; ?></li>
                <?php 
                endwhile;
                else:
                ?>
                <li class="no-items">There are no messages yet.</li>
                <?php endif; ?>
                </ul>
                <?php mysql_free_result($result); ?>
            </td>
            <td width="50%">
                <h4>Send Us Message</h4>
                <form method="POST" id="send-message">
                    <input name="message" rows="10" style="width: 100%;" placeholder="Enter message and hit Enter" />
                </form>
            </td>
        </tr>
    </tbody>
</table>
<script>
jQuery( function(){
    // Form Submission
    jQuery('#send-message').submit( function(){
        var message = jQuery('#send-message input[name=message]').val();
        if( jQuery.trim( message ) == '' ){
            alert('Enter a message!');
            return false;
        }

        jQuery.ajax({
            url: 'submit.php',
            type: 'POST',
            data: 'message=' + message,
            dataType: 'json',
            success: function( payload ){
                if( payload.status == 'error' ){
                    alert('Error!');
                } else if( payload.status == 'empty-message' ){
                    alert('Enter a message!');
                } else if( payload.status == 'success' ){
                    jQuery('#send-message input[name=message]').val('');
                }
            }
        });
        return false;
    });

    // Start Long-polling for messages
    function messages_longpolling( timestamp, lastId ){
        var t;

        if( typeof lastId == 'undefined' ){
            lastId = 0;
        }

        jQuery.ajax({
            url: 'stream.php',
            type: 'GET',
            data: 'timestamp=' + timestamp + '&lastId=' + lastId,
            dataType: 'json',
            success: function( payload ){
                clearInterval( t );
                if( payload.status == 'results' || payload.status == 'no-results' ){
                    t=setTimeout( function(){
                        messages_longpolling( payload.timestamp, payload.lastId );
                    }, 1000 );
                    if( payload.status == 'results' ){
                        jQuery.each( payload.data, function(i,msg){
                            if( jQuery('.no-items').size() == 1 ){
                                jQuery('.items').empty();
                            }
                            if( jQuery('#' + msg.id).size() == 0 ){
                                jQuery('.items').prepend( '<li id="' + msg.id + '">' + msg.id + '. ' + msg.message + '</li>' );
                            }
                        });
                    }
                } else if( payload.status == 'error' ){
                    alert('We got confused, Please refresh the page!');
                }
            },
            error: function(){
                clearInterval( t );
                t=setTimeout( function(){
                    messages_longpolling( payload.timestamp, payload.lastId );
                }, 15000 );
            }
        });
    }
    messages_longpolling( '<?php echo time(); ?>' );
});
</script>
stream.php
<?php 
require_once('global.php');

$timestamp = (int) trim( $_GET['timestamp'] );
$lastId = isset( $_GET['lastId'] ) && !empty( $_GET['lastId'] ) ? $_GET['lastId'] : 0;

if( empty( $timestamp ) ){
    die( json_encode( array( 'status' => 'error' ) ) );
}

$time_wasted = 0;
$lastIdQuery = '';
if( !empty( $lastId ) ){
    $lastIdQuery = ' AND ID > ' . $lastId;
}

$new_messages_check = mysql_query("SELECT * FROM messages WHERE msg_time >= {$timestamp}" . $lastIdQuery ." ORDER BY ID DESC");
$num_rows = mysql_num_rows( $new_messages_check );
if( $num_rows <= 0 ){
    while( $num_rows <= 0 ){
        if( $num_rows <= 0 ){


            sleep( 1 );
            $new_messages_check = mysql_query("SELECT * FROM messages WHERE msg_time >= {$timestamp}" . $lastIdQuery . " ORDER BY ID DESC");
            $num_rows = mysql_num_rows( $new_messages_check );
            $time_wasted += 1;
        }
    }
}

$new_messages = array();
if( $num_rows >= 1):
while ( $row = mysql_fetch_array( $new_messages_check, MYSQL_ASSOC ) ):
    $new_messages[] = array( 'id' => $row['ID'], 'message' => $row['msg_text'] );
endwhile;
endif;
$last_msg = end( $new_messages );
$last_id = $last_msg['id'];

die( json_encode( array( 'status' => 'results', 'timestamp' => time(), 'lastId' => $last_id, 'data' => $new_messages ) ) );
?>

msg_time是int 11

0 个答案:

没有答案