SSE SseEmitter.completeWithError(e) 触发的处理逻辑

Java 客户端使用 OkHttp 监听 SSE(Server-Sent Events) 的情况下,当服务端调用 SseEmitter.completeWithError(e),客户端会触发 EventSourceListeneronFailure() 方法(而不是 onError)。


1. 服务端(Spring Boot)调用 completeWithError

java 复制代码
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

@RestController
public class SseController {

    @GetMapping("/sse-stream")
    public SseEmitter streamEvents() {
        SseEmitter emitter = new SseEmitter();

        new Thread(() -> {
            try {
                for (int i = 0; i < 5; i++) {
                    emitter.send(SseEmitter.event().data("Event " + i));
                    Thread.sleep(1000);
                }
                // 模拟一个错误并主动关闭
                throw new RuntimeException("Server-side error!");
            } catch (Exception e) {
                emitter.completeWithError(e); // 触发客户端的 onFailure()
            }
        }).start();

        return emitter;
    }
}

2. 客户端(Java + OkHttp)监听 SSE

OkHttp 提供了 EventSource 类来监听 SSE 事件,并需要实现 EventSourceListener 来接收回调。

关键方法

  • onOpen() -- 连接建立时触发。
  • onEvent() -- 收到服务器事件时触发。
  • onClosed() -- 服务器主动关闭(emitter.complete())时触发。
  • onFailure() -- 服务器调用 completeWithError() 或网络错误时触发

代码示例

java 复制代码
import okhttp3.*;
import okhttp3.sse.EventSource;
import okhttp3.sse.EventSourceListener;
import okhttp3.sse.EventSources;

public class SseClient {
    public static void main(String[] args) {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder()
                .url("http://localhost:8080/sse-stream")
                .build();

        EventSource.Factory factory = EventSources.createFactory(client);
        factory.newEventSource(request, new EventSourceListener() {
            @Override
            public void onOpen(EventSource eventSource, Response response) {
                System.out.println("SSE connected!");
            }

            @Override
            public void onEvent(EventSource eventSource, String id, String type, String data) {
                System.out.println("Received event: " + data);
            }

            @Override
            public void onClosed(EventSource eventSource) {
                System.out.println("SSE closed by server.");
            }

            @Override
            public void onFailure(EventSource eventSource, Throwable t, Response response) {
                System.err.println("SSE error: " + t.getMessage());
                // 可以在这里重试
            }
        });
    }
}

3. 执行流程

  1. 服务端
    • 发送5条事件后,调用 emitter.completeWithError(e)
  2. 客户端
    • 收到5条正常事件(onEvent())。
    • 当服务端 completeWithError(e) 时,触发 onFailure(),并打印错误信息。

4. 总结

服务端行为 客户端(OkHttp)回调方法
emitter.send(data) onEvent()
emitter.complete() onClosed()
emitter.completeWithError(e) onFailure()
网络断开/超时 onFailure()

因此,SseEmitter.completeWithError(e) 会触发客户端的 onFailure() 方法 ,而不是 onError(这是浏览器 EventSource 的行为)。

相关推荐
泡海椒2 分钟前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp
泡海椒3 小时前
JQuick-Curl 二次开发:自定义解析器、扩展点开发指南,如何把框架能力真正变成团队资产
java·开发语言·okhttp·maven
摇滚侠1 天前
《SpringBoot 3:入门与应用实战》第 9 章 跨域问题 阅读笔记 27
spring boot·笔记·okhttp
刘广睿3 天前
断点续传与分片下载是怎么实现的?Range 请求在视频下载中的工程实践
okhttp·ffmpeg·音视频·下载·python3.11
泡海椒8 天前
JQuick-Curl vs RestTemplate / OkHttp / OpenFeign:框架选型对比,谁更适合第三方接口调用?
okhttp
Co_Hui11 天前
OkHttp 原理
okhttp
殷忆枫12 天前
BOA服务器下实现视频回放功能(CGI+软链接方案)
服务器·okhttp·音视频
消失的旧时光-194314 天前
第十篇:Ktor Custom Client Plugin:从 OkHttp Interceptor 真正理解请求与响应生命周期
okhttp·plugin·ktor·kmp
mmsx14 天前
基于 Android 的校园信息管理系统源码
android·java·okhttp
Full Stack Developme21 天前
跨站请求伪造 (CSRF) 是什么 设计及工作原理
前端·okhttp·csrf