码迷,mamicode.com
首页 > 其他好文 > 详细

我的第一个comet长连接例子

时间:2016-02-29 23:20:28      阅读:189      评论:0      收藏:0      [点我收藏+]

标签:

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<meta content="text/html; charset=UTF-8" http-equiv="Content-Type">
<title>Comet Test</title>
<script src="../statics/js/jquery-1.9.1.min.js"></script>
</head>
<body>
<script type="text/javascript">
$(function(){
    function handleResponse(response){
    $(#content).append(<div> + response[msg] + </div>);
    }
 
    var timestamp = 0;
    var url = server.php;
    var noerror = true;
    var ajax;
 
    function connect() {
        ajax = $.ajax(url, {
            type: get,
            data: { timestamp : timestamp },
            success: function(transport) {
                eval(var response = +transport);
                timestamp = response[timestamp];
                handleResponse(response);
                noerror = true;
            },
            complete: function(transport) {
                (!noerror) && setTimeout(function(){ connect() }, 5000) || connect();
                noerror = false;
            }
        });
    }
 
    function doRequest(request) {
        $.ajax(url, {
            type: get,
            data: { msg : request }
        });
    };
    
    $(#cometForm).on("submit",function(){
        
        doRequest($(#word).val());
        $(#word).val(‘‘);
        return false;
    });
    
    
    connect();

});
</script>
<div id="content"></div>
<div style="margin: 5px 0;">
<form action="javascript:void(0);" id="cometForm" method="get">
<input id="word" name="word" type="text" value="">
<input name="submit" type="submit" id="btn" value="Send">
 
</form></div>
</body>
</html>

 

<?php
 
$filename  = ‘F:\phpStudy\WWW\boss\cometDemo\data.txt‘;

// 消息都储存在这个文件中
$msg = isset($_GET[‘msg‘]) ? $_GET[‘msg‘] : ‘‘;

if ($msg != ‘‘){
    //fopen()方法:如果文件不存在,则创建,如果存在则打开文件。它的第二个参数是打开的文件的模式,w表示覆盖式只写,详见《PHP高程设计》183页
    $fn = fopen($filename,‘w‘);
    fwrite($fn,$msg);
    fclose($fn);
//    file_put_contents($filename,$msg); 此方法已不建议使用
    
}

    // 不停的循环,直到储存消息的文件被修改
    $lastmodif    = isset($_GET[‘timestamp‘]) ? $_GET[‘timestamp‘] : 0;
    $currentmodif = filemtime($filename);
    while ($currentmodif <= $lastmodif){ // 如果数据文件已经被修改
        usleep(100000); // 100ms暂停 缓解CPU压力
        clearstatcache(); //清除缓存信息
        $currentmodif = filemtime($filename);
    }
 
    // 返回json数组
    $response = array();
    $response[‘msg‘]       = file_get_contents($filename);
    $response[‘timestamp‘] = $currentmodif;
    echo json_encode($response);
    flush();

 
?>

自备jquery1.9.1,并改写下txt文件的路径

我的第一个comet长连接例子

标签:

原文地址:http://www.cnblogs.com/macliu/p/5229170.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!