【问题标题】:server send events with spring mvc always closed服务器发送带有spring mvc的事件总是关闭
【发布时间】:2017-06-13 07:18:20
【问题描述】:

我做了一个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

【问题讨论】:

  • 如果您需要调试帮助,至少提供预期的和服务的行为,“告诉我出了什么问题”是不够的。另请阅读help centerHow to Ask

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-04-22
    • 2014-09-29
    • 2013-11-09
    • 2019-10-19
    • 1970-01-01
    • 2021-04-22
    • 1970-01-01
    • 2018-10-07
    相关资源
    最近更新 更多