簡體   English   中英

流套接字和服務器發送事件

[英]stream socket and server sent event

我再次在使用stream_socket的實時系統上工作,並在客戶端服務器上發送了事件...因為即時消息者既不聰明也無法自行解決案例。

這就是使用udp ..從一台服務器更新到該服務器的事情,並希望通過服務器發送的事件或其他事件向用戶生動地顯示數據,而無需使用api或庫。

PHP代碼

<?php
$socket = stream_socket_server("udp://127.0.0.1:7755", $errno, $errstr,STREAM_SERVER_BIND);
if (!$socket) {
die ( "$errstr ($errno)<br />\n");
} 
while (true) {
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$got= stream_socket_recvfrom($socket, 1500);// just say im getting time update every 1 second from the sender
echo $got;
flush();
}


?>

js部分

var source = new EventSource("receive.php");
source.onmessage = function(event) {
document.getElementById("result").innerHTML + =event.data + "<br>";
 };

了解到php在完全執行之前不會回顯。 我將嘗試更多選擇以保持連接打開,而不是再次請求文件。 暫時來說,這仍然可以正常工作,但是仍然有一些數據包丟失了,但是仍然可以工作。

的PHP

<?php
$sock=stream_socket_server("udp://127.0.0.1:7755",$errno,$errstr,STREAM_SERVER_BIND);

if (!$sock) { 
 die("$errstr ($errno)"); 
} 

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

$d=stream_socket_recvfrom($sock, 1500); 

echo "data: {$d}\n\n";

flush();
?>

JS

var source = new EventSource("receive.php");
 source.onmessage = function(event) {
 document.getElementById("result").innerHTML + =event.data + "<br>";
};

暫無
暫無

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

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