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'.