ResponseBodyReader.java
1.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
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);
}
}