dd

服务器推送数据到客户端(可做直播)

jerry PHP 2015年11月18日 收藏
服务器推送数据到客户端,可实现直播或者一些其他特殊需求。。。(类似每次苹果大会还有爱范儿直播那种东西。如果拿ajax 去定时查询的太累了,实现原理comet 技术)甚至可以执行js css 等代码~

后台前端部分代码~
    function send(msg){
        $.ajax({
            data : {'msg' : msg},
            type : 'post',
            url : '{:U('Live/SendMsg')}',
            success : function(response){
               //alert(response);;
            }
        })
    }
    $(document).ready(function(){
        connect();
        $("#btn").click(function(){
            var msg = $('#msg').val();
            send(msg);
            msg.html('');
          });
    })
    public function SendMsg(){
        
        $filename  = './Uploads/live/'.'data.json';
        if ($_POST['msg']!='') {
            file_put_contents($filename,$_POST['msg']);
            $this->ajaxReturn($_POST,'OK',100);
            die();
        }else{
            $this->ajaxReturn($_POST,'on',0);
            die();
        }
        
    }
前台展示部分:
 <div id="infobox" >
1.请输入推送信息,可同时执行多条信息和JavaScript指令,每行一条<br/></div>
 var timestamp = 0;
    var url = '/live.php';
    var error = false;
    function connect(){
        $.ajax({
            data : {
                'timestamp' : timestamp
            },
            url : url,
            type : 'get',
            timeout : 0,
            success : function(response){
                var data = eval('('+response+')');
                error = false;
                timestamp = data.timestamp;
                if (data.msg!='') 
                {
                    $("#infobox").append(data.msg + '<br>');
                };
                
            },
            error : function(){
                error = true;
                setTimeout(function(){ connect();}, 5000);
            },
            complete : function(){
                if (error)
                    // if a connection problem occurs, try to reconnect each 5 seconds
                    setTimeout(function(){connect();}, 5000);
                else
                    connect();
            }
        })
    }
   $(document).ready(function(){
      connect();
    })
推送模块代码:
<?php 
    $filename  = './Uploads/live/'.'data.json';
//    $msg = isset($_GET['msg']) ? $_GET['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);
    //$this->ajaxReturn($response,'ok',1);
    flush();
?>


现在有个bug 好像是属于tp 内核的吧?在前端页面执行过推送,在去点tp 框架里面其他功能会变得很卡,大概卡顿30秒左右不知道是什么原因还在找,目前采用的是文件读写判断修改时间 然后去推送。也就是说你那个文件只要修改就会去推送到本地客户端,里面可以执行js html css 等你想要的效果。
期待大神优化~

dd