简体   繁体   English

我使用服务器发送的事件(和Javascript / PHP)建立的连接一直在立即断开

[英]My connection using Server-Sent Events (and Javascript/PHP) keeps dropping immediately

Yesterday I dived into Server-Sent events, as they were a great way to create a newsfeed for an online game I'm creating. 昨天,我深入研究了Server-Sent事件,因为它们是为正在创建的在线游戏创建新闻源的好方法。 I had a working script that could subscribe to my feed, and a script that could pull the newsfeed from the MySql database within minutes, but for some reason it drops the connection every time... (and reconnects every 3 seconds, making it nothing better than just using AJAX with certain time intervals for example) 我有一个可以订阅我的提要的工作脚本,一个可以在几分钟之内从MySql数据库中提取新闻提要的脚本,但是由于某种原因,它每次都断开连接……(每3秒重新连接一次,什么也没做比仅以特定时间间隔使用AJAX更好)

The javascript I'm using: 我正在使用的javascript:

var source = new EventSource('http://theobg.itselementary.site50.net/gamefeed.php');
source.onmessage = function(e) {
    $("#gamefeed").html(e.data);
}

The PHP I'm using: 我正在使用的PHP:

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

function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}

//The file for connecting to my database here...
$gameid = 1;

$serverTime = time();
//Some mysql query to get the gamefeed from the database here..., gamefeed is structured like this: NEWS&OTHERNEWS&OLDERNEWS&EVENOLDERNEWS

sendMsg($serverTime, $gamefeed);

?>

I've looked all over the internet, but everything seems to work fine with me, except for the connection not being 'kept alive', and I have no clue as to why that is...can anybody help me? 我看了遍整个互联网,但似乎一切正常,除了连接没有“保持活动”,而且我不知道为什么……有人可以帮助我吗?

Thanks in advance, Dalionzo 在此先感谢Dalionzo

You need to check the data and send it using a loop. 您需要检查数据并使用循环将其发送。

<?php
while(true){
    //check for updates here
    if($updates){
        sendMsg($id,$data);
    }
    sleep(1);//loosen it up
}

Also, for easier coding you can try my php library for Server-sent Events. 另外,为了简化编码,您可以尝试使用我的PHP库进行服务器发送的事件。 Here 这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM