如何在SSE spring-web中发送“ping”事件

huangapple go评论60阅读模式
英文:

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

问题

我正在尝试在Java中实现graphql-sse规范,并且希望能够发送心跳事件以实现这一目标。这可以通过发送事件来完成:

到事件流中。但是,为了能够做到这一点,我不能发送一个ServerSentEvent对象,因为它要求您构建一个完整的对象,而这不是一个完整的对象,只是一个空事件。我也找不到任何关于Spring如何ping客户端以查看连接是否仍然打开的文档。

非常感谢任何帮助。

英文:

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.

答案1

得分: 1

You can emit a "ping" event like this: ServerSentEvent.builder("").data(null).comment("").build(). 这将在文本流中产生 :\n\n

I had to read through the source code for the ServerSentEventHttpMessageWriter.

这段代码是通过使用带有 : 前缀的注释来生成事件,以便客户端忽略它。然后,因为注释只是一个空字符串,它将在后面添加 \n,并且因为没有设置其他字段,它还将在末尾添加另一个 \n。请注意,我只需使用 builder("") 来让我的类型工作(至少暂时是这样的)。

在Kotlin中,你可以使用 ServerSentEvent.builder<String>().comment("").build()

英文:

TLDR: You can emit a "ping" event like so: ServerSentEvent.builder(&quot;&quot;).data(null).comment(&quot;&quot;).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&lt;String&gt;().comment(&quot;&quot;).build()

huangapple
  • 本文由 发表于 2023年4月13日 17:53:33
  • 转载请务必保留本文链接:https://go.coder-hub.com/76004062.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定