Search code examples
javaspring-mvcgraphqlhttp2server-sent-events

How to send a "ping" event in SSE spring-web


I'm trying to implement the graphql-sse specification in java, and to be able to do this I want to be able to send a heartbeat event. This can be done by sending the event: :\n\n to the event-stream.

However to be able to do this I can't send a ServerSentEvent object because it requires you to build a full object whereas this isn't a full object this is just an empty event. I also can't see any documentation on spring pinging the client to see if the connection is still open.

Any help would be greatly appreciated.


Solution

  • TLDR: You can emit a "ping" event like so: ServerSentEvent.builder("").data(null).comment("").build()

    This will produce :\n\n in the text stream.

    I had to read through the source code for the ServerSentEventHttpMessageWriter

    The code produces the event by using a comment which is prefixed with : so the client ignores it. And then because the comment is just an empty string it will add the \n afterwards and because there are no other fields set it will add another \n at the end. Note I only had to use builder("") to get my type working (for now anyway).

    In kotlin you can use ServerSentEvent.builder<String>().comment("").build()