php模拟长连接 (3353 views)

不耳

2017-01-17 17:02:27

例1:循环延迟输出数据

<?php

if (ob_get_level() == 0) ob_start();

for ($i = 0; $i<10; $i++){

        echo "<br> Line to show.";
        echo str_pad('',4096)."\n";    

        ob_flush();
        flush();
        sleep(2);
}

echo "Done.";

ob_end_flush();

?>

例2: 输出一些字符,达到条件后跳转

<?php
$web = "<h1>hello world</h1>";
echo $web;
ob_flush();
flush();

$data = 1;

while (1) {
sleep(1);
$data++;
if($data == 5) {
echo "<meta http-equiv='Refresh' content='0;URL=return.php'>";
break;
}
}

例3:输出一些字符,达到条件后跳转。

<?php
$web = "<h1>hello world</h1>";
echo $web;
ob_flush();
flush();

while (1) {
$fp = fopen("s.txt", "r");
if(fgets($fp) == 1) {
echo "<meta http-equiv='Refresh' content='0;URL=return.php'>";
break;
}
fclose($fp);
sleep(1);
} 

laravel下写的一个实例,读取缓存的变化 控制器:

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\Http\Requests;

use Cache;

class ScanLoginController extends Controller
{
    private $_cacheKey = 'longlink';

    public function index()
    {
        Cache::put($this->_cacheKey, 0, 0);

        return view('test.index');
    }

    public function login(Request $request)
    {
        $i = 0;
        while ($i < 250) {
            $fp = Cache::get($this->_cacheKey);
            if($fp == 1) {
                return ['status' => 1];
            }

            $i++;

            usleep(100000);
        }

        return ['status' => 0];
    }

    public function confirm()
    {
        Cache::put($this->_cacheKey, 1, 0);

        dump(Cache::get($this->_cacheKey));
    }
}

视图:

<html>
<head>
    <title>test</title>
    <meta charset="UTF-8">
    <script src="//cdn.bootcss.com/jquery/3.1.0/jquery.min.js"></script>
    <script>
    $(function () {
        function longlink() {
            $("#show").text("正在连接");

            $.get("{{ route('login') }}", function (data) {
                if(data.status === 1) {
                    $("#show").text("有反应了");
                } else {
                    $("#show").text("没反应,继续");
                    longlink();
                }
            }, "json");
        }

        $("#begin").click(function () {
            longlink();
        });
    });
    </script>
</head>
<body>
    <div class="container">
        <h1>长连接</h1>
        <button id="begin" class="btn btn-success">开始</button>
        <div id="show">我是一个长连接</div>
    </div>
</body>
</html> 
Tags: php 长连接