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)
The case class play.api.libs.EventSource.Event always formats the line with a data: prefix. Hence pure comments / heartbeats can't be send.
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
Most helpful comment
Hey @an-tex,
Yes, makes sense to support event comments, maybe as a new field in
play.api.libs.EventSource.Eventor even as its own type. For now, a possible workaround is to send events withevent: heartbeat, for example:And on the client side have an event listener for
heartbeat.