【问题标题】:EventSource onmessage() is not working where onopen() and onerror() works properly?EventSource onmessage() 在 onopen() 和 onerror() 正常工作的地方不起作用?
【发布时间】:2015-04-24 18:03:20
【问题描述】:

检查下面的代码,这里我为每种事件类型添加了三个警报消息,但在此代码中 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( )。

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

【问题讨论】:

    标签: java javascript


    【解决方案1】:

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

    例如:

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

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

    【讨论】:

    • 谢谢,这是我的问题。
    【解决方案2】:

    我认为正确的格式是:

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

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

    【讨论】:

    • 经过数小时的挠头和许多标签打开后,这对我有用。指定客户端将要监听的事件。
    • 谢谢,这是我的问题。
    【解决方案3】:

    解决了!!!

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

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

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

    疯狂的编码..

    【讨论】:

    • 谢谢你,额外的 \n 为我解决了这个问题。哎呀,多么古怪的格式要求。
    • 一个换行符不足以区分事件
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-03-05
    • 2017-08-09
    • 2019-04-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多