Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/456.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/294.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 流套接字和服务器发送事件_Javascript_Php - Fatal编程技术网

Javascript 流套接字和服务器发送事件

Javascript 流套接字和服务器发送事件,javascript,php,Javascript,Php,再一次,我正在使用stream_socket开发一些实时系统,并在客户端服务器上发送事件……因为我既不专业,也不够聪明,无法自己解决这个问题 下面是我使用udp从一台服务器更新到这个服务器的事情。我希望通过服务器发送的事件或其他方式向用户显示数据,而不使用API或库 php代码 <?php $socket = stream_socket_server("udp://127.0.0.1:7755", $errno, $errstr,STREAM_SERVER_BIND); if (!$soc

再一次,我正在使用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>";
 };
var source=neweventsource(“receive.php”);
source.onmessage=函数(事件){
document.getElementById(“结果”).innerHTML+=event.data+“
”; };
了解到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>";
};
var source=neweventsource(“receive.php”);
source.onmessage=函数(事件){
document.getElementById(“结果”).innerHTML+=event.data+“
”; };
EventSource基于HTTP,而不是UPD。你只需要稍微修改一下HTTP响应就可以使用EventSource.感激你的评论..我正在尝试我能想到的,但仍然让我感到有限。