服务器发送的事件和php-是什么触发服务器上的事件? [英] Server-sent events and php - what triggers events on the server?

查看:72
本文介绍了服务器发送的事件和php-是什么触发服务器上的事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

全部

HTML5 Rocks提供了有关服务器发送事件(SSE)的不错的初学者教程:

HTML5 Rocks has a nice beginner tutorial on Server-sent Events (SSE):

http://www.html5rocks.com/en/tutorials/eventsource/basics /

但是,我不了解一个重要的概念-是什么触发了服务器上导致邮件发送的事件?

But, I don't understand an important concept - what triggers the event on the server that causes a message to be sent?

换句话说-在HTML5示例中-服务器仅发送一次时间戳一次:

In other words - in the HTML5 example - the server simply sends a timestamp once:

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
function sendMsg($id, $msg) {
  echo "id: $id" . PHP_EOL;
  echo "data: $msg" . PHP_EOL;
  echo PHP_EOL;
  ob_flush();
  flush();
}
$serverTime = time();
sendMsg($serverTime, 'server time: ' . date("h:i:s", time()));

如果我要建立一个实际的例子-例如,Facebook风格的墙"或股票行情自动收录器,其中每当某些数据发生更改时,服务器都会向客户端推送"一条新消息.那工作吗?

If I were building a practical example - e.g., a Facebook-style "wall" or a stock-ticker, in which the server would "push" a new message to the client every time some piece of data changes, how does that work?

换句话说... PHP脚本是否具有一个连续运行的循环,检查数据中的更改,然后在每次发现一个消息时发送一条消息?如果是这样-您如何知道何时结束该过程?

In other words... Does the PHP script have a loop that runs continuously, checking for a change in the data, then sending a message every time it finds one? If so - how do you know when to end that process?

或者-PHP脚本是否只是发送消息,然后结束(如HTML5Rocks示例所示)?如果是这样-您如何获得持续更新?浏览器是否只是按固定的时间间隔轮询PHP页面?如果是这样-那服务器发送事件"如何?这与用JavaScript编写setInterval函数有何不同?该函数使用AJAX定期调用PHP页面?

Or - does the PHP script simply send the message, then end (as appears to be the case in the HTML5Rocks example)? If so - how do you get continuous updates? Is the browser simply polling the PHP page at regular intervals? If so - how is that a "server-sent event"? How is this different from writing a setInterval function in JavaScript that uses AJAX to call a PHP page at a regular interval?

对不起-这可能是一个非常幼稚的问题.但是我找不到的所有例子都没有清楚地说明这一点.

Sorry - this is probably an incredibly naive question. But none of the examples I've been able to find make this clear.

[更新]

我认为我的问题措辞不好,所以这里有一些澄清.

I think my question was poorly worded, so here's some clarification.

假设我有一个网页,其中应显示苹果股票的最新价格.

Let's say I have a web page that should display the most recent price of Apple's stock.

当用户首次打开页面时,页面会创建一个带有我流"的URL的EventSource.

When the user first opens the page, the page creates an EventSource with the URL of my "stream."

var source = new EventSource('stream.php');

我的问题是-"stream.php"应如何工作?

My question is this - how should "stream.php" work?

喜欢吗? (伪代码):

Like this? (pseudo-code):

<?php
    header('Content-Type: text/event-stream');
    header('Cache-Control: no-cache'); // recommended to prevent caching of event data.
    function sendMsg($msg) {
        echo "data: $msg" . PHP_EOL;
        echo PHP_EOL;
        flush();
    }

    while (some condition) {
        // check whether Apple's stock price has changed
        // e.g., by querying a database, or calling a web service
        // if it HAS changed, sendMsg with new price to client
        // otherwise, do nothing (until next loop)
        sleep (n) // wait n seconds until checking again
    }
?>

换句话说-只要客户端连接"到它,"stream.php"是否保持打开状态?

In other words - does "stream.php" stay open as long as the client is "connected" to it?

如果是-这是否意味着运行stream.php的线程数与并发用户数一样?如果是这样-远程可行还是构建应用程序的适当方法?以及如何知道何时可以 END stream.php的实例?

If so - does that mean that you have as many threads running stream.php as you have concurrent users? If so - is that remotely feasible, or an appropriate way to build an application? And how do you know when you can END an instance of stream.php?

我的天真的印象是,如果是这种情况,PHP 不是适合这种服务器的技术.但是到目前为止,我看过的所有演示都暗示PHP对此非常合适,这就是为什么我如此困惑的原因.

My naive impression is that, if this is the case, PHP isn't a suitable technology for this kind of server. But all of the demos I've seen so far imply that PHP is just fine for this, which is why I'm so confused...

推荐答案

"...只要客户端处于连接"状态,"stream.php"是否保持打开状态 呢?"

"...does "stream.php" stay open as long as the client is "connected" to it?"

是的,您的伪代码是一种合理的方法.

Yes, and your pseudo-code is a reasonable approach.

您怎么知道何时可以终止stream.php的实例?"

"And how do you know when you can END an instance of stream.php?"

在最典型的情况下,这种情况发生在用户离开您的网站时. (Apache识别了关闭的套接字,并杀死了PHP实例.)您可能主要是从服务器端关闭套接字的主要时间是,如果您知道一段时间内将没有数据,那么可以关闭该套接字.您发送给客户的最后一条消息是告诉他们在特定时间回来.例如.在进行股票流传输的情况下,您可以在晚上8点关闭连接,并告诉客户在8小时内回来(假设纳斯达克在凌晨4点至晚上8点开放报价).星期五晚上,您告诉他们星期一早上回来. (我即将出版一本有关SSE的书,并专门讨论了该主题的两个部分.)

In the most typical case, this happens when the user leaves your site. (Apache recognizes the closed socket, and kills the PHP instance.) The main time you might close the socket from the server-side is if you know there is going to be no data for a while; the last message you send the client is to tell them to come back at a certain time. E.g. in your stock-streaming case, you could close the connection at 8pm, and tell clients to come back in 8 hours (assuming NASDAQ is open for quotes from 4am to 8pm). Friday evening you tell them to come back Monday morning. (I have an upcoming book on SSE, and dedicate a couple of sections on this subject.)

"...如果是这种情况,则PHP不适合这种技术 服务器.但是到目前为止,我看过的所有演示都暗示PHP是 对此很好,这就是为什么我如此困惑..."

"...if this is the case, PHP isn't a suitable technology for this kind of server. But all of the demos I've seen so far imply that PHP is just fine for this, which is why I'm so confused..."

好吧,人们认为PHP不是适用于普通网站的技术,而且它们是对的:如果用C ++替换整个LAMP堆栈,则可以用更少的内存和CPU周期来做到这一点.但是,尽管如此,PHP仍然可以很好地支持大多数站点.由于结合了熟悉的类似于C的语法和如此众多的库,因此它对于Web工作而言是一种非常高效的语言,它为经理提供了一种令人欣慰的方式,使他们可以雇用大量的PHP程序员,大量的书籍和其他资源,以及一些大型的PHP程序员.用例(例如Facebook和Wikipedia).这些基本上就是您可能选择PHP作为流技术的相同原因.

Well, people argue that PHP isn't a suitable technology for normal web sites, and they are right: you could do it with far less memory and CPU cycles if you replaced your whole LAMP stack with C++. However, despite this, PHP powers most of the sites out there just fine. It is a very productive language for web work, due to a combination of a familiar C-like syntax and so many libraries, and a comforting one for managers as plenty of PHP programmers to hire, plenty of books and other resources, and some large use-cases (e.g. Facebook and Wikipedia). Those are basically the same reasons you might choose PHP as your streaming technology.

典型的设置不是每个PHP实例仅一个到NASDAQ的连接.取而代之的是,您将拥有另一个与NASDAQ的单一连接,或者从集群中每台计算机到NASDAQ的单一连接的进程.然后将价格推到SQL/NoSQL服务器或共享内存中.然后,PHP只会轮询该共享内存(或数据库),并将数据推出.或者,拥有一个数据收集服务器,并且每个PHP实例都打开一个到该服务器的套接字连接.数据收集服务器在收到每个PHP客户端更新时将其推送出去,然后依次将这些数据推送到其客户端.

The typical setup is not going to be one connection to NASDAQ per PHP-instance. Instead you are going to have another process with a single connection to the NASDAQ, or perhaps a single connection from each machine in your cluster to the NASDAQ. That then pushes the prices into either a SQL/NoSQL server, or into shared memory. Then PHP just polls that shared memory (or database), and pushes the data out. Or, have a data-gathering server, and each PHP instance opens a socket connection to that server. The data-gathering server pushes out updates to each of its PHP clients, as it receives them, and they in turn push out that data to their client.

使用Apache + PHP进行流传输的主要可伸缩性问题是每个Apache进程的内存.当您达到硬件的内存限制时,请做出业务决策,将另一台计算机添加到群集,或者将Apache退出循环,并编写专用的HTTP服务器.后者可以用PHP完成,因此您所有现有的知识和代码都可以重复使用,或者您可以用另一种语言重写整个应用程序.在我看来,纯粹的开发人员会用C ++编写专用的,简化的HTTP服务器.我内的经理会添加另一个框.

The main scalability issue with using Apache+PHP for streaming is the memory for each Apache process. When you reach the memory limit of the hardware, make the business decision to add another machine to the cluster, or cut Apache out of the loop, and write a dedicated HTTP server. The latter can be done in PHP so all your existing knowledge and code can be re-used, or you can rewrite the whole application in another language. The pure developer in me would write a dedicated, streamlined HTTP server in C++. The manager in me would add another box.

这篇关于服务器发送的事件和php-是什么触发服务器上的事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆