Playframework: EventSource.Event (SSE) can't be used to send comments / keep alive messages

Created on 26 Mar 2019  ·  4Comments  ·  Source: playframework/playframework

Play Version (2.7.0)

API (Scala)

Expected Behavior

It should be possible to send comment events using play.api.libs.EventSource.Event (aka ServerSentEvents / SSE). These events start with a colon and can be used to keep the connection alive, e.g.:

: this is a keep alive message

data: some actual event with data

As described in https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#Examples

This way you could keep a connection alive by e.g.:

Ok.chunked(source.via(EventSource.flow).keepAlive(50.seconds, () => heartbeatEvent)).as(ContentTypes.EVENT_STREAM)

Actual Behavior

The case class play.api.libs.EventSource.Event always formats the line with a data: prefix. Hence pure comments / heartbeats can't be send.

help wanted

Most helpful comment

Hey @an-tex,

Yes, makes sense to support event comments, maybe as a new field in play.api.libs.EventSource.Event or even as its own type. For now, a possible workaround is to send events with event: heartbeat, for example:

val heartbeatEvent = Event(data = heartbeatData, name = Some("heartbeat"))
Ok.chunked(source.via(EventSource.flow).keepAlive(50.seconds, () => heartbeatEvent)).as(ContentTypes.EVENT_STREAM)

And on the client side have an event listener for heartbeat.

All 4 comments

Hey @an-tex,

Yes, makes sense to support event comments, maybe as a new field in play.api.libs.EventSource.Event or even as its own type. For now, a possible workaround is to send events with event: heartbeat, for example:

val heartbeatEvent = Event(data = heartbeatData, name = Some("heartbeat"))
Ok.chunked(source.via(EventSource.flow).keepAlive(50.seconds, () => heartbeatEvent)).as(ContentTypes.EVENT_STREAM)

And on the client side have an event listener for heartbeat.

Yep that workaround works. I'll try to squeeze in a PR over the next weeks.

Hey @marcospereira since I don't see any further updates in this issue, may I work on this? Any pointer would be helpful thanks!

Hi @fusuiyi123 , sorry I totally forgot about that. From my side feel free to take over. Cheers

Was this page helpful?
0 / 5 - 0 ratings