Undertow 2.X ServerSentEventHandler 未将数据流式传输到客户端

问题描述 投票:0回答:1

我有以下 Undertow 2.x ServerSentEventHandler 代码

public class SimpleServer {

  public static void main(String[] args) {
    Undertow server = Undertow.builder()
            .addHttpListener(8080, "localhost")
            .setHandler(new ServerSentEventHandler((connection, lastEventId) -> {

                for (int i = 0; i < 10; i++) {
                    System.out.println("LastEventId: " + lastEventId + ", i: " + i);
                    connection.send("Numbers :: " + i);

                    try {
                        Thread.sleep(500);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            })).build();
    server.start();
  }
}

具有以下 Maven 依赖项

    <dependency>
        <groupId>io.undertow</groupId>
        <artifactId>undertow-core</artifactId>
        <version>2.3.12.Final</version>
    </dependency>
    <dependency>
        <groupId>com.networknt</groupId>
        <artifactId>server</artifactId>
        <version>0.1.1</version>
    </dependency>

当我点击 API 时,我在控制台上看到以下日志

LastEventId: null, i: 0
LastEventId: null, i: 1
LastEventId: null, i: 2
LastEventId: null, i: 3
LastEventId: null, i: 4
LastEventId: null, i: 5
LastEventId: null, i: 6
LastEventId: null, i: 7
LastEventId: null, i: 8
LastEventId: null, i: 9

打印完所有这些日志后,我会在浏览器上同时获取所有数字(而不是每个数字在可用时立即进行流式传输)。我尝试过使用 Postman、curl,但行为仍然相同。我在响应标头中添加了 "no-cache" 标头,但没有用。有谁知道我如何将数据从服务器stream传输到客户端?它与缓冲/缓存等有什么关系吗?另外,我不知道为什么 lastEventId 总是 null

java server-sent-events undertow
1个回答
0
投票

在不同的线程上运行流逻辑解决了该问题。

public class SimpleServer {

  public static void main(String[] args) {
     ExecutorService executorService = Executors.newCachedThreadPool();
     Undertow server = Undertow.builder()
        .addHttpListener(8080, "localhost")
        .setHandler(new ServerSentEventHandler((connection, lastEventId) -> {
          executorService.submit(() -> {
            for (int i = 0; i < 10; i++) {
                System.out.println("LastEventId: " + lastEventId + ", i: " + i);
                connection.send("Numbers :: " + i);

                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }})).build();
     server.start();
 }
}
© www.soinside.com 2019 - 2024. All rights reserved.