最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Why is this EventSource repeatedly triggering message and error? - Stack Overflow

programmeradmin0浏览0评论

Client side looks like this:

var es = new EventSource("http://localhost:8080");
es.addEventListener("message", function(e) {
    alert("e.data") //Alerts "" every couple seconds
})
es.addEventListener("error", function(e) {
    alert("error") //Also fires every couple of seconds
})
var post_request = new XMLHttpRequest();
post_request.open("POST", "http://localhost:8080");
post_request.setRequestHeader("Content-Type", "text/plain");
post_request.addEventListener("readystatechange", function() {
    if (post_request.readyState == 4 && post_request.status == 200) {
        alert(post_request.responseText); //This works
    }
})
post_request.send("This is a test")

Server side Node.js handling POST request looks like this:

function process_request(request, response) {
    var request_body = []
    request.on("data", function(chunk) {
        request_body.push(chunk)
    }) 
    request.on("end", function() {
        request_body = Buffer.concat(request_body).toString()+"\n"
        response.writeHead(200, {"Access-Control-Allow-Origin": "*",
                                 "Content-Type": "text/event-stream",
                                 "Connection": "keep-alive"
                                });

        response.end("data: " + request_body + "\n"); 
    })
}

If I send POST request data from the client side, it gets returned to me with response.end() as expected, but es is triggering an error every couple of seconds, in addition to a message event every couple of seconds. When themessage event is triggered, however, it alerts "", and I'm not sure why? Can anyone help me figure out this behavior?

EDIT: Just checked the es.readyState on the message and error events. readyState is 0 on the error, so it seems like it might be a result of getting disconnected. Why would this repeated disconnecting happen? And why would repeated connecting and disconnecting cause repeated message events?

Client side looks like this:

var es = new EventSource("http://localhost:8080");
es.addEventListener("message", function(e) {
    alert("e.data") //Alerts "" every couple seconds
})
es.addEventListener("error", function(e) {
    alert("error") //Also fires every couple of seconds
})
var post_request = new XMLHttpRequest();
post_request.open("POST", "http://localhost:8080");
post_request.setRequestHeader("Content-Type", "text/plain");
post_request.addEventListener("readystatechange", function() {
    if (post_request.readyState == 4 && post_request.status == 200) {
        alert(post_request.responseText); //This works
    }
})
post_request.send("This is a test")

Server side Node.js handling POST request looks like this:

function process_request(request, response) {
    var request_body = []
    request.on("data", function(chunk) {
        request_body.push(chunk)
    }) 
    request.on("end", function() {
        request_body = Buffer.concat(request_body).toString()+"\n"
        response.writeHead(200, {"Access-Control-Allow-Origin": "*",
                                 "Content-Type": "text/event-stream",
                                 "Connection": "keep-alive"
                                });

        response.end("data: " + request_body + "\n"); 
    })
}

If I send POST request data from the client side, it gets returned to me with response.end() as expected, but es is triggering an error every couple of seconds, in addition to a message event every couple of seconds. When themessage event is triggered, however, it alerts "", and I'm not sure why? Can anyone help me figure out this behavior?

EDIT: Just checked the es.readyState on the message and error events. readyState is 0 on the error, so it seems like it might be a result of getting disconnected. Why would this repeated disconnecting happen? And why would repeated connecting and disconnecting cause repeated message events?

Share Improve this question edited Apr 20, 2016 at 5:35 digglemister asked Apr 20, 2016 at 1:43 digglemisterdigglemister 1,4873 gold badges17 silver badges31 bronze badges 2
  • For one thing, "This is a test" is not a valid in text/event-stream content. Did you try actually writing a valid response body? – mscdex Commented Apr 20, 2016 at 1:55
  • @mscdex I've edited to make it a valid text/event-stream content. Now what happens is that the es triggers both a message event and an error event every couple of seconds. However, on message event, alert(e.data) alerts an empty string? – digglemister Commented Apr 20, 2016 at 2:16
Add a ment  | 

1 Answer 1

Reset to default 7

What is happening is you are processing the user's SSE request, sending back some data, then closing the connection. The client sees the connection has been lost, and reconnects a couple of seconds later (this reconnect is a feature of SSE).

So, instead, you should never exit. That means you need to make sure that request.on("end", ... is never reached.

Here is a basic SSE server in node.js that I've used before:

var http = require("http");
var port = parseInt( process.argv[2] || 8080 );

http.createServer(function(request,response){
  console.log("Client connected:" + request.url);
  response.writeHead(200, { "Content-Type": "text/event-stream" });
  var timer = setInterval(function(){
    var content = "data:" + new Date().toISOString() + "\n\n";
    response.write(content);
    }, 1000);
  request.connection.on("close", function(){
    response.end();
    clearInterval(timer);
    console.log("Client closed connection. Aborting.");
    });
  }).listen(port);
console.log("Server running at http://localhost:" + port);

I.e. we use a setInterval to keep running. The only event to listen for is the client closing the connection.

发布评论

评论列表(0)

  1. 暂无评论