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

时间:2015-02-23 12:01:56

标签: java javascript

检查下面的代码,这里我为每种事件类型添加了三条警报消息,但在此代码中,source.onopen()[alert:readyState:1]和source.onerror()[alert:readyState: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工具套装),我想知道,当我在EventSource(源)对象上使用ctrl + space时,在选项中它只显示onopen()和onerror(),其中是onmessage( )。

如果我得到任何回复,我将非常感激。 --Thanks

3 个答案:

答案 0 :(得分:10)

解决了!!!

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

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

在我的代码中,我错过了响应对象中的最后一部分“\ n \ n”,因此javascript中的source.onmessage(datalist)没有被点击。

疯狂编码..

答案 1 :(得分:4)

我认为正确的格式是:

out.write("event: message\n");
out.write("data:" + value + "\n\n");

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

答案 2 :(得分:1)

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

例如:

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

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

相关问题