[英]Server-Sent Events from PHP polling mySQL
后台需要定期将数据发送到连接到Web应用程序的客户端。 这是我设置的脚本:
<?php
header("Content-Type: text/event-stream\n\n");
header('Cache-Control: no-cache');
flush();
ob_flush();
require_once('connect.php');
//connect to the database
$mysql = mysql_connect($hostname, $username, $password) or die ('cannot reach database');
$db = mysql_select_db($database) or die ("this is not a valid database");
mysql_query("SET NAMES 'utf8'", $mysql);
$query = mysql_query("SELECT * FROM `clientEvents` ORDER BY id DESC LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array($query);
$index = $row["id"];
echo $index;
loop($index);
function loop($index){
while (1)
{
ob_implicit_flush(true);
$buffer = str_repeat(" ", 4096);
echo $buffer."\n";
// Every second, look for new question.
$query = mysql_query("SELECT * FROM `clientEvents` WHERE id>$index ORDER BY id DESC LIMIT 1") or die(mysql_error());
$row = mysql_fetch_array($query);
if(mysql_num_rows($query)>0)
{
if($row["type"]=="pushCustomQuestion"){
pushCustomQuestion($row["data"],$row["id"]);
break;
}
else if($row["type"]=="pushGameTimeEvent"){
pushGameTimeEvent($row["data"],$row["id"]);
break;
}
}
sleep(3);
}
function pushGameTimeEvent($id,$index) {
//echo "id for game event:".$id;
$result = mysql_fetch_array(mysql_query("SELECT * FROM game_events WHERE id = $id LIMIT 1"));
//$num_results = mysql_num_rows($result);
echo "event: new_game_event\n";
echo 'data: { "id": "' . $result['id'] . '",'
.'"match_id": "' . $result['match_id'] . '",'
.'"minute": "' . $result['minute'] . '",'
.'"event_id": "' . $result['event_id'] . '",'
.'"event_name": "' . $result['event_description'] . '",'
.'"player_name": "' . $result['player1_name']. '",'
.'"player2_name": "' . $result['player2_name'] . '",'
.'"which_half": "' . $result['which_half'] . '",'
.'"team_logo": "' . $result['team_logo'] . '"}';
echo "\n\n";
ob_flush();
flush();
sleep(10);
loop($index);
}
一切正常,直到有七个客户端将所有东西都加载到Web应用程序上为止。 脚本本身有问题吗?
在我看来,这样做的方式是违反直觉的,因为我正在轮询数据库以发送新事件。 还有其他更好的方法可以从后台应用程序触发事件吗?
谢谢你的帮助。
这可能与Apache所限制的一次可进行连接的人数有关。
这是一个很棒的长轮询教程,与您设置的有点不同: http : //elikirk.com/2012/04/17/php-ajax-long-polling-comet-demonstration/
但是,如果您希望扩展此范围,则长轮询不是实时“推送”的最佳解决方案。
我建议您看一下node.js和sockets.io,因为这些技术是专门为此目的而设计的。 缺点是node.js本质上是运行javascript的自己的服务器,因此您将不得不放弃php。 但是有一些解决方法,您可以通过CURL桥接node.js和php。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.