javascript - 服务器发送事件,spring mvc 始终关闭

标签 javascript java spring-mvc server-sent-events

我做了一个sse演示,但它不起作用,我发布了js和java代码,请告诉我哪里出了问题,谢谢。

这是js:

if (window.EventSource) {
    var source = new EventSource('http://127.0.0.1:8080/pushweb/push');
    source.addEventListener('message', function(e) {
        console.log(e.data, this.readyState);
    },false);

    source.addEventListener('open', function(e) {
        console.log("conncted",this.readyState);
    },false);
    source.addEventListener('error', function(e) {
        if (e.target.readyState == EventSource.CLOSED) {
            console.log("closed");
        } else if(e.target.readyState == EventSource.CONNECTING){
            console.log("connecting");
        }else {
            console.log("error"+this.readyState);
        }
    }, false);
} else {
    console.log("not support SSE");
}

这是 springmvc 代码:

@CrossOrigin(origins = "*", maxAge = 3600)
@Controller
public class PushController
{
@RequestMapping(value = "/push", produces = "text/event-stream;charset=UTF-8")
@ResponseBody
public String push()
{
    String str =Long.toString(System.currentTimeMillis());
    return "data:"+str + "\n\n\n";
}

@RequestMapping(value = "/message")
@ResponseBody
public String message()
{
    String stre = "hello";
    return stre;
}

}

this is the chrome console result

最佳答案

在服务器端,需要使用SseEmitter来发送事件。请参阅Server-Sent Events with Spring (博客)。

关于javascript - 服务器发送事件,spring mvc 始终关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44514751/

相关文章:

java - JPA 中的引用完整性约束违规错误

java - Spring消息未出现在jsp页面上

java - 2 model.setAttribute方法中的对象

javascript - 忽略元素 html 的验证 - Jquery 验证

javascript - 在 JavaScript 中可以实现数组减法的最快数量级是多少?

java - 将程序转换为使用对象而不是数字

java - 使用 JPA 存储库查询三个属性

javascript - 缓慢打开/关闭 div?

javascript - 无法链接另一个身份验证方法 - firebase auth

java - 如何在 Android 的菜单选项中添加带有文本的图像?