如何使用 PHP 在 POST 上发送 Server Sent Events?

How send Sever Sent Events on POST using PHP?

我只是从 PHP 和服务器发送的事件开始。 在查看了几篇文章之后,比如 W3C and HTML5Rocks 一篇,我能够非常快地开始做一些事情。

我现在要做的是在我的 php 脚本收到 POST 时发送服务器发送事件。这是我天真的尝试的样子:

<?php

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

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

$method = $_SERVER['REQUEST_METHOD'];

if ($method == 'POST') {

    $serverTime = time();
    $data = file_get_contents("php://input");

    sendMsg($serverTime,$data);

}

?>

这似乎行不通,但我不明白为什么。 我看不到任何错误,使用 JS 我可以看到客户端可以连接, 但是执行 POST 操作时没有数据通过。

当服务器收到 POST 时发送服务器发送事件的推荐方式是什么?

我将直接引用 my SSE book,第 9 章,"HTTP POST with SSE" 部分:

If you bought this book just to learn how to POST variables to an SSE backend, and you’ve turned straight to this section, I’d like you to take a deep breath, and make sure you are sitting down. You see, I have some bad news. ... The SSE standard has no way to allow you to POST data to the server. This is a very annoying oversight, ...

备选方案是回到 SSE 之前的备选方案(因为 XMLHttpRequest,即 AJAX,确实允许 POST);这本书确实涵盖了相当详细的内容。

实际上,还有另一种解决方法,考虑到您使用的是 PHP,这实际上相当简单:首先 post 将数据传输到另一个脚本,用它来存储您的 POST $_SESSION 中的数据,然后让您的 SSE 脚本将其从 $_SESSION 中取出。 (这并不像听起来那么难看:SSE 过程将很长 -运行,因此可以接受一个额外的 http 调用来设置它。)