簡體   English   中英

HTML5服務器發送的事件

[英]HTML5 Server-Sent Event

我正在嘗試使用SSE構建實時應用程序。 但是,當我認為我以正確的方式編寫所有內容時,它是行不通的。 請幫我解決這個問題。 我知道websockets比SSE更好,但是我一開始就在這里,這是我的index.html代碼

 <!DOCTYPE html> <html> <head> <title>Using SSE(Server-sent event)</title> <meta charset="utf-8"> </head> <body> <h1>Getting server updates</h1> <div id="result"></div> <script> if(typeof(EventSource) !== "undefined") { var source = new EventSource("getdata.php"); source.onmessage = function(event) { console.log(JSON.parse(event.data)); }; } else { document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events..."; } </script> </body> </html> 

這是getdata.php頁面

   <?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache');

    $pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
    $obj = $pdo->query("select * from users");
    $arr = $obj->fetchAll();
    echo "data: ".json_encode($arr);
    flush();
   ?>

當我用

source.onerror = function(er){
   console.log(er);   
}

我懂了

error { target: EventSource, isTrusted: true, currentTarget: EventSource, eventPhase: 2, bubbles: false, cancelable: false, defaultPrevented: false, composed: false, timeStamp: 5152.813223, cancelBubble: false, originalTarget: EventSource }

我在html console.log(JSON.parse(event.data))中嘗試了注釋代碼; 但它也不起作用。

請幫助理解SSE的工作原理,我的代碼有什么問題?

提前致謝。

我發現了為什么它不起作用。 我加了\\ n \\ n

echo "data: ".json_encode($arr);

所以看起來像這樣

echo "data: ".json.encode($arr)."\n\n";

希望對您有所幫助

編輯 (只是為了將來的觀眾而離開)

檢查 (然后在瀏覽器中按F12並檢查“控制台”-它在Firefox和Chrome中對我有效)

完全按照該服務器上的代碼查看代碼:

sse.html

<!DOCTYPE html>
<html>
<head>
<title>Using SSE(Server-sent event)</title>
<meta charset="utf-8">
</head>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>
if(typeof(EventSource) !== "undefined") {
    var source = new EventSource("getdata.php");
    source.onmessage = function(event) {  
        console.log(JSON.parse(event.data));
    };
} else {
    document.getElementById("result").innerHTML = "Sorry, your browser does not support server-sent events...";
}
</script>

</body>
</html>

getdata.php(由於是舊服務器,仍然是mysql,而不是msqli或PDO)

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

include("../../admin2/config.inc.php");
connect_db();
$query = mysql_query( "select * from ttbb" ) or die( mysql_error() );
$arr = mysql_fetch_object( $query );
echo "data: ".json_encode($arr)."\n\n";
flush();
?>

打印: 在此處輸入圖片說明

首先,也是最重要的是,PHP腳本應該永遠運行,而不是執行一個查詢然后死亡。 (如果這是您的意圖,那么您就不需要流解決方案,而應該使用AJAX。)

其次,每個data::之后需要兩個LF data:: 而且(可能)除了flush()之外,您還可能需要ob_flush() flush() 經過這三個更改,看起來像這樣:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$pdo = new PDO("mysql:host=localhost;dbname=sse", 'root', 'secret');
while(true){  //Deliberate infinite loop
  $obj = $pdo->query("select * from users");
  $arr = $obj->fetchAll();
  echo "data: ".json_encode($arr)."\n\n";
  @ob_flush();@flush();  //Use @ to suppress v.rare but meaningless errors
  sleep(1);  //Poll the database every second.
  }

?>

我已將其(服務器)設置為每秒輪詢本地數據庫。 您應該根據服務器負載與目標延遲之間的平衡來調整此值。

重要說明:這將每秒將所有用戶數據發送到所有客戶端。 您應該重新設計SQL查詢,以僅提取自上次查詢以來已更改的用戶。 然后重新設計前端,以便在第一次呼叫時為所有用戶提供服務,然后再進行更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM