使用EventSource发送文本文件内容

时间:2014-01-06 04:30:09

标签: javascript php

我想使用EventSource发送文本文件的内容(在服务器上)。这是文件的内容(data.txt):

2
0.42 1.30 -0.77 1.18 -0.03 1.56 0.42 0.11 -0.03 -1.95
0.40 -0.69 0.24 -0.26 0.63 0.68 0.20 -1.06 1.94 0.63

我使用EventSource的原因是因为此文件将始终更新。这是服务器端PHP代码(getData.php):

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

$fid = fopen("data.txt", "r");
$N = fgets($fid);

for ($i=0; $i<$N; $i++) {
    $line = fgets($fid);
    $data[$i] = explode(" ", $line);
}
fclose($fid);

echo "data: {$N}\n";
for ($i=0; $i<1; $i++) {
    for ($j=0; $j<9; $j++) {
        echo "data: {$data[$i][$j]}\n";
    }
}
echo "data: {$data[0][9]}\n\n";
flush();
?>

以下是客户端的HTML代码:

<html>
<head>
<script type="text/javascript" language="javascript">
var dataStr;

if(typeof(EventSource) !== "undefined") {
    var source=new EventSource("getData.php");
    source.onmessage = function(event) {
        dataStr = event.data;
    };
}
else {
    alert("Sorry, your browser does not support server-sent events.");
}

function changeVal() {
    document.getElementById("result").innerHTML = dataStr;
}
</script>
</head>

<body>
<p id="result">This is a test.</p>
<br/>
<button type="button" onclick="changeVal()">Elements</button>
</body>
</html>

当我打开HTML文件并单击按钮时,显示的项目仅为:

0.42 1.30 -0.77 1.18 -0.03 1.56 0.42 0.11 -0.03 -1.95

而不是

2 0.42 1.30 -0.77 1.18 -0.03 1.56 0.42 0.11 -0.03 -1.95

正如我所料。

我为EventSource尝试了一个较短的数据,并按如下方式修改了PHP代码:

...
echo "data: {$N}\n";
echo "data: {$data[0][9]}\n\n";
...

按钮点击仅显示-1.95,而不显示2 -1.95

我的PHP代码有什么问题吗?我可以实际混合字符串和数组类型并使用EventSource将它们发送到客户端吗?

1 个答案:

答案 0 :(得分:0)

请尝试以下代码。

它输出为

 2 0.42 1.30 -0.77 1.18 -0.03 1.56 0.42 0.11 -0.03 -1.95 0.40 -0.69 0.24 
 -0.26 0.63 0.68 0.20 -1.06 1.94 0.63

希望有所帮助

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

$fid = fopen("data.txt", "r");

while(!feof($fid))
{
  $line =  fgets($fid);
  $data[] = explode(" ", $line);
}

fclose($fid);

foreach($data as $dat){
    foreach($dat as $d){
        echo "data: ". trim($d,$charlist = " \t\n\r\0\x0B" ) ."\n";
    }
}

echo "\n\n";
flush();
?>