EventSource onmessage()在onopen()和oneror()正常工作的地方不起作用



检查下面的代码,在这里,我为每个事件类型添加了三条警报消息,但在这个代码中,source.onpen()[aler:readyState:1]和source.onerror()[aalert:readySate:0]工作正常,但在onmessage()的情况下,它没有执行。`

       if(typeof(EventSource) !== "undefined") {
           var source = new EventSource('clinic/get');
           source.onopen = function(){
             alert('connection is opened.'+source.readyState);  
           };
           source.onerror = function(){
               alert('error: '+source.readyState);
           };
           source.onmessage = function(datalist){
               alert("message: "+datalist.data);
           };
        } else {
            document.getElementById("clinic-dtls").innerHTML = "Sorry, your browser does not support server-sent events...";
        }`

检查下面的服务器端代码

Random random = new Random();
        response.setContentType("text/event-stream");
        response.setCharacterEncoding("UTF-8");
        System.out.println("clinic/get got hit");
        try {
            Writer out = response.getWriter();
            out.write("data: welcome data"+random);
            out.flush();
            out.close();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

我正在使用STS(Spring tool Suits),我想知道,当我在EventSource(source)对象上使用ctrl+space时,在选项中它只显示onopen()和oneror(),其中是onmessage()。

如果我能得到任何回复,我将不胜感激--感谢

我认为正确的格式是:

out.write("event: messagen");
out.write("data:" + value + "nn");

onmessage处理程序假定事件名称为message。如果要使用其他事件名称,可以使用addEventListener订阅它们。

解决了它!!!

代码没有问题,实际问题是当我向客户端写响应时,我的响应消息应该如下所示。

PrintWriter out = response.write("data: message"+value+"nn");
out.flush(); //don't forget to flush

在我的代码中,我缺少响应对象中的最后一个部分"\n\n",所以javascript中的source.onmessage(datalist)没有被命中。

疯狂的编码。。

请检查流的类型。如果传入事件流类型为"onMessage",则默认情况下将触发onMessage;消息";这只是默认类型。事件流中缺少默认事件字段导致此问题

例如:

a) Stream.emit("push", "message", { msg: "price Chnage" }); // this works

b) Stream.emit("push", "test", { msg: "price Chnage" }); // this won't

最新更新