使用 sseclient 在 Python 中读取服务器端事件

Reading Server Side Events in Python using sseclient

我是服务器端事件的新手,使用 sseclient 库在服务器端 PHP 和客户端 Python 开始了一些测试。

使用非常基本的 PHP 脚本,基于 w3schools tutorial 我可以看到在 Python 中收到的数据:

<?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();
}


$time = date('r');
// echo "data: The server time is: {$time}\n\n";
// flush();
sendMsg(time(),"The server time is: {$time}\n\n");


?>

并在 Python 中:

#!/usr/bin/env python
from sseclient import SSEClient

messages = SSEClient('http://pathto/myscript.php')
for msg in messages:
    print msg

作为第二步,我尝试发送从存储在 $_SESSION 变量中的数组读取的数据。当我在浏览器中从 javascript 连接到 SSE 流时,这似乎有效,但它不起作用,我不确定为什么。

这是我的基本 PHP 脚本:

<?php

session_start();

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();
}

// check for session data
if (isset($_SESSION["data"])){

    #as long there are elements in the data array, stream one at a time, clearing the array (FIFO)
    while(count($_SESSION["data"]) > 0){

        $serverTime = time();
        $data = array_shift($_SESSION["data"]);
        sendMsg($serverTime,$data);

    }
}

?>

和Python脚本是一样的。

为什么 sseclient Python 脚本没有从上面的 PHP 脚本中获取事件(而基本的 JS 脚本可以)?

PHP 会话变量作为 cookie 发送;如果您使用 Firebug(或等效)查看您的 JavaScript 版本,您应该看到 cookie 被发送到 SSE 服务器脚本。

因此您需要为 Python 脚本设置一个会话,并将其也发送到 cookie 中。

您可以通过在 PHP 脚本中添加一些错误处理来证实这个猜测:

...
if (isset($_SESSION["data"])){
   //current code here
}else{
   sendMsg(time(), "Error: no session");
}