[英]Spring boot: SSE Server Sent Events not working
In Spring Boot, when we try to send a Server Sent Event, it only sends an error event containing data: {"timeout":-1} when we try to connect, and the connection closes.在 Spring Boot 中,当我们尝试发送 Server Sent Event 时,它仅在我们尝试连接时发送一个包含 data: {"timeout":-1} 的错误事件,然后连接关闭。 The Spring Boot class is as follows Spring启动class如下
@RestController
@CrossOrigin(origins = "*")
public class SsePushNotificationRestController {
private static final Logger log = LoggerFactory.getLogger(SsePushNotificationRestController.class);
private SseEmitter emitter;
@GetMapping("/test")
public String getString(){
try {
emitter.send("User connected");
log.info("User connected");
emitter.complete();
} catch (Exception e) {
log.info("Error while sending message to client: " + e.getMessage());
}
return "placeholder";
}
@GetMapping("/emitter")
public SseEmitter eventEmitter(@RequestParam String userId) {
emitter = new SseEmitter(-1L);
return emitter;
}
}
And our client code is as follows:而我们的客户端代码如下:
const eventSource = new EventSource('http://localhost:8080/emitter?userId=testUser');
eventSource.addEventListener("message", (event) => {
console.log(event);
});
eventSource.addEventListener("open", (event) => {
console.log("connection opened");
});
eventSource.addEventListener("error", (e) => {
if (e.readyState === EventSource.CLOSED) {
console.log('closed');
}
else {
console.log(e);
}
e.target.close();
});
document.getElementById("btn").onclick = e => {
fetch('http://localhost:8080/test').then( data => console.log(data)).catch(data => console.log(data));
};
Immediately, an error is created before we can click the button to generate an event.立即,在我们可以单击按钮生成事件之前创建一个错误。 What could be wrong?有什么问题?
What does your Spring boot terminal say?你的 Spring 启动终端说什么? I think I need that information to address your program's error.我想我需要这些信息来解决您的程序错误。 By the way allowing cross origin resources sharing for requests from any sources (using wildcard) is a very very bad practice.顺便说一句,允许跨源资源共享来自任何来源的请求(使用通配符)是一种非常非常糟糕的做法。
One possible reason of error is something's wrong when you create an instance of SSEemitter.一个可能的错误原因是当您创建 SSEemitter 实例时出现问题。 (new SSeEmitter(-1L)) (新的 SSeEmitter(-1L))
SSeEmitter(Long timeout) is creating server side event with set timeout it says. SSeEmitter(Long timeout) 正在创建设置超时的服务器端事件。 So if timeout is -1, I guess it would immediately be timed out and return timeout response.所以如果超时为-1,我猜它会立即超时并返回超时响应。 So it wouldn't be error, just working as written所以它不会是错误的,就像写的那样工作
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.