ResponseBodyReader.java 1.1 KB
package com.zhonglai.luhui.sse;

import okio.BufferedSource;

import java.io.IOException;

 public class ResponseBodyReader {
    private final BufferedSource source;

    public ResponseBodyReader(BufferedSource source) {
        this.source = source;
    }

    public boolean hasNextEvent() throws IOException {
        // 判断是否还有下一个SSE事件
        return !source.exhausted();
    }

    public ServerSentEvent nextEvent() throws IOException {
        // 读取下一个SSE事件
        String id = null;
        String event = null;
        String data = null;

        while (true) {
            String line = source.readUtf8LineStrict();
            if (line.isEmpty()) {
                break;  // SSE事件结束
            }

            if (line.startsWith("id:")) {
                id = line.substring(3).trim();
            } else if (line.startsWith("event:")) {
                event = line.substring(6).trim();
            } else if (line.startsWith("data:")) {
                data = line.substring(5).trim();
            }
        }

        return new ServerSentEvent(id, event, data);
    }
}