Search code examples
phpserver-sent-eventseventsource

Unable to send custom events with SSE and PHP


I have Server Sent Events (SSE) working with the default message type. But I'm unable to get a custom event type to work.

On the client I have

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

On the server I have

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

}

Running this code, you can see the event: test\n is commented out, and I get the SSE with type message in my browser. But if I uncomment the event: test\n to try and change the event type to test, the client side listener does not invoke ( nor does the default message type). Am I missing something here?? Thanks for any help.


Solution

  • Try to change the quotes from :

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

    To :

    echo("event: test\n");
    

    To allow new line to be processed