-1

I have a configured nginx server instance which works together with some Node.js instances like this:

nginx part:

upstream app_nodeSocketServer {
   server 127.0.0.1:3001;
}

[...]

location /nodeSocket {
   proxy_pass http://app_nodeSocketServer/;
}

Node.js part:

var express = require('express');
var app = express();
var os = require("os");


app.get('/', function (req, res) {

    res.writeHead(200, {
      "Content-Type": "text/event-stream",
      "Cache-Control": "no-cache",
      "Connection": "keep-alive"
    });

//    var interval = setInterval(function() {
      res.write("data: Uptime: " + os.uptime() + "\n\n");
      res.end();
//    }, 1000);


  /*  req.connection.addListener("close", function () {
      clearInterval(interval);
    }, false);*/

});


app.listen(3001, function () {
  console.log('Example app listening on port 3001!');
});

So if I call http://domain/nodeSocket the node.js part is invoked and a response is displayed.

Using it with server sent events:

<html>
<head>
</head>
<body>

<h1>Getting server updates</h1>
<div id="result"></div>

<script>

    var url = "http://domain/nodeSocket";
    var source = new EventSource(url);
    source.onmessage = function(event) {
        console.log(event.data);
        document.getElementById("result").innerHTML = event.data + "<br>";
    };
</script>

This is also working.

Question

In all examples which use Node.js together with server sent events I do not see any line res.end(). But when I remove this line from my code the events where not displayed anymore.

What is the reason for this behaviour?

At the moment the server side event client call is invoked every three seconds because this is the standard reconnect value after the server side has closed its connection.

As I understand the server side must not close the connection but sending data until the client gets 'destroyed'.

sk2212
  • 1,688
  • 4
  • 23
  • 43
  • https://nodejs.org/en/about/ event the simplest server code has `res.end()` – Alexey Ten Mar 31 '16 at 08:06
  • Have a look at `https://segment.com/blog/2014-04-03-server-sent-events-the-simplest-realtime-browser-spec/` or `http://stackoverflow.com/questions/31700336/server-sent-event-eventsource-with-node-js-express`. There are no `res.end()` calls. For a simple node server you are right but not when using it with SSEs. Did you downvote because of this? – sk2212 Mar 31 '16 at 08:14
  • Ah, in your case you have to disable nginx's proxy buffering, otherwise nginx waits for end of response before answering to client. See http://nginx.org/r/proxy_buffering – Alexey Ten Mar 31 '16 at 08:19
  • Yeah, that works. Could you please provide this as an answer? – sk2212 Mar 31 '16 at 08:23

1 Answers1

1

You have to disable nginx's proxy buffering, otherwise nginx waits for end of response before answering to client. See http://nginx.org/r/proxy_buffering for details

Alexey Ten
  • 13,794
  • 6
  • 44
  • 54