4

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?

digglemister
  • 1,477
  • 3
  • 16
  • 31
  • 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 Apr 20 '16 at 01: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 Apr 20 '16 at 02:16

1 Answers1

4

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.

Darren Cook
  • 27,837
  • 13
  • 117
  • 217