将数据从服务器推送到用户浏览器

2022-08-30 20:06:22

我想将数据从服务器推送到浏览器。我已经知道发送输出缓冲区的php函数。我需要一些逻辑方面的帮助。我正在使用Facebook实时API,所以我想在每次Facebook访问我的网站时将数据推送给用户。ob_flush()

这是我的代码,我试图将数据推送到浏览器,但它不起作用。

<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/event-stream');
ini_set("log_errors", 1);
ini_set("error_log", "php-error.log");
error_log( "LOGS STARTS FROM HERE" );
if(isset($_GET['hub_challenge'])){
    echo $_GET['hub_challenge'];    
}
if($_SERVER['REQUEST_METHOD'] == "POST"){
    $updates = json_decode(file_get_contents("php://input"), true); 
    // Replace with your own code here to handle the update 
    // Note the request must complete within 15 seconds.
    // Otherwise Facebook server will consider it a timeout and 
    // resend the push notification again.
    print_r($updates);
    ob_flush();
    flush();
    //file_put_contents('fb.log', print_r($updates,true), FILE_APPEND);     
    //error_log('updates = ' . print_r($updates, true));              
}
?>

答案 1

正如@som建议的那样,您可以简单地使用请求,它们之间有间隔,您不需要使用套接字。

但问题是,您正在尝试从API接收数据并将其直接传递到浏览器,所有这些都是一次性的。最好将这两个步骤分开。

在从 Facebook 接收数据的脚本中,将该数据存储在数据库或其他位置:

if($_SERVER['REQUEST_METHOD'] == "POST"){
    $updates = json_decode(file_get_contents("php://input"), true); 

    insertDataToDatabase($updates); // you'll have to implement this.
}

然后设置监控页面:

监视器.php

<script>
lastId = 0;

$(document).ready(function() {
    getNewDataAtInterval();
});

function getNewDataAtInterval() {
    $.ajax({
        dataType: "json",
        url: "getData.php",
        data: {lastId: lastId}
    }).done(function(data) {
        for(i=0; i<data.messages.length; i++) {
            $("#messages").append("<p>" + data.messages[i]['id'] + ": " + data.messages[i]['message'] + "</p>");
            if (data.messages[i]['id'] > lastId) lastId = data.messages[i]['id'];
        }

        setTimeout(getNewDataAtInterval, 10000);
    }).fail(function( jqXHR, textStatus ) {
        alert( "Request failed: " + jqXHR.responseText );
    });
}
</script>

<div id="messages"></div>

最后,创建一个服务器端脚本以返回一个 JSON,其中包含从数据库加载的新消息。

获取数据.php

$lastId = $_GET['lastId'];
$newMessages = getUpdatesFromDatabase($lastId);

exit(json_encode(array("messages"=>$newMessages)));

function getUpdatesFromDatabase($lastId) {
    // I'm using this array just as an example, so you can see it working.
    $myData = array(
        array("id"=>1,"message"=>"Hi"),
        array("id"=>2,"message"=>"Hello"),
        array("id"=>3,"message"=>"How are you?"),
        array("id"=>4,"message"=>"I'm fine, thanks")
    );

    $newMessages = array();
    foreach($myData as $item) {
        if ($item["id"] > $lastId) {
            $newMessages[] = $item;
            $newLastId = $item["id"];
        }
    }

    return $newMessages;
}

答案 2

使用彗星或原型将是这里的最佳实践。Ajax 将增加服务器负载。它将频繁轮询服务器。以下是有关使用彗星的一些必要信息。

以下是如何使用php实现comet以发送实时数据的示例。


推荐