gpt4 book ai didi

javascript - Java 服务器不使用 OutboundSseEvent/JAX-RS 服务器发送事件 (SSE) 服务发送消息事件

转载 作者:行者123 更新时间:2023-12-01 21:48:17 25 4
gpt4 key购买 nike

我已经在 J​​ava 服务器中设置了 SSE(服务器发送事件)。客户端基于 VueJS 构建,并使用 EventSource 包从服务器接收事件。我正在使用 EventSourcePolyfill npm 包 https://www.npmjs.com/package/event-source-polyfill在客户端上。该包允许我们随请求发送授权 header (用于我们的安全方案)。

客户端向我们的 SSE 服务发送请求并接收类型为“open”的单个事件。然后,SSE 不再发送进一步的事件,或者发送事件但浏览器不会检测到它们。为什么是这样?修复建议?没有错误消息。

此行为发生在 Chrome、Firefox 和 Edge 中,因此可能与浏览器无关。

Our client method...
testSSE() {
console.log("in testSSE()");
console.log("apikey: " + store.user.apikey);
var EventSource = EventSourcePolyfill;

const evtSource = new EventSource(
"http://localhost:8081/api/ssetest/test",
{ headers: { Authorization: "Bearer " + store.user.apikey } }
);
evtSource.onmessage = function(event) {
console.log("received message");
console.log("event.data: " + event.data);
};

//This is the only function that gets hit
evtSource.addEventListener("open", function(event) {
console.log("open event");
console.log(Object.keys(event));
console.log(event.type);
});
evtSource.addEventListener("message", function(event) {
console.log("message event");
});
evtSource.addEventListener("stringEvent", function(event) {
console.log("received ping event");
console.log("event.data: " + event.data);
});
evtSource.onerror = function(err) {
console.error("EventSource failed:", JSON.stringify(err));
};
}

这是我们的服务器代码...@Path(“ssetest”)公共(public)类 SSETestService 扩展 SecureService {

@GET
@Path("/test")
@Produces("text/event-stream")
public void runTest(@Context Sse sse, @Context SseEventSink sseEventSink)
{
int lastEventId = 0;// ..;
while (lastEventId < 10) {
OutboundSseEvent stringEvent = sse.newEventBuilder()
.name("" + lastEventId)
.mediaType(MediaType.APPLICATION_JSON_TYPE)
.data("hello world")
.id(String.valueOf(lastEventId))
.reconnectDelay(4000) // .comment("price change")
.build();
sseEventSink.send(stringEvent);
lastEventId++;
TimeUnit.SECONDS.sleep(1);

}
}

}

Browser console output...
[![enter image description here][1]][1]


[1]: /image/iR57U.png

最佳答案

我也有类似的问题。将 @Produces 值切换为“application/stream+json”为我解决了这个问题。

关于javascript - Java 服务器不使用 OutboundSseEvent/JAX-RS 服务器发送事件 (SSE) 服务发送消息事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58775265/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com