无法使用SSE和PHP发送自定义事件

问题描述 投票:0回答:1

我有使用默认消息类型的服务器发送事件(SSE)。但是我无法使自定义事件类型起作用。

关于我的客户

const sse = new 
EventSource('/api/events/transaction-event');
sse.onopen = (d=>console.log(d))

sse.addEventListener("message", function(e) {
  console.log('message')
  console.log(e)
})

sse.addEventListener("test", function(e) {
  console.log('test')
  console.log(e)
})

在服务器上,我有

class Events
{
    public function test(Request $request){
      $response = new StreamedResponse(function() use ($request) {
        while(true) {

          // echo('event: test\n');
          echo 'data: ' . json_encode(['hello'=>'world']) . "\n\n";
          ob_flush();
          flush();
          sleep(2);
        }
      });
      $response->headers->set('Content-Type', 'text/event-stream');
      $response->headers->set('Connection', 'keep');
      $response->headers->set('Cache-Control', 'no-cache');
      return $response;
    }

}

运行此代码,您可以看到event: test\n被注释掉了,并且在浏览器中我得到了类型为message的SSE。但是,如果我取消注释event: test\n以尝试将事件类型更改为test,则客户端侦听器不会调用(默认message类型也不会)。我在这里想念什么吗?感谢您的帮助。

php server-sent-events eventsource
1个回答
0
投票

尝试更改引号:

// echo('event: test\n');

收件人:

echo("event: test\n");

为了处理回车

© www.soinside.com 2019 - 2024. All rights reserved.