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

新手上路,请多包涵

检查下面的代码,在这里我为每个事件类型添加了三个警报消息,但在此代码中 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 tool Suits),我想知道,当我在 EventSource(源)对象上使用 ctrl+space 时,在选项中它只显示 onopen() 和 onerror(),onmessage() 在哪里。

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

原文由 Ram 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 2.3k
2 个回答

解决了!!!

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

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

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

疯狂编码..

原文由 Ram 发布,翻译遵循 CC BY-SA 3.0 许可协议

我认为正确的格式是:

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

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

原文由 Pappa 发布,翻译遵循 CC BY-SA 3.0 许可协议

推荐问题