The backend first has a basic_sse.php page:
<?php
header("Content-Type: text/event-stream");
while(true){
echo "data:".date("Y-m-d H:i:s")."\n\n";
@ob_flush();@flush();
sleep(1);
}
?>
You can use Apache Server so that we can place them on sinaappengine. when you access firefox1_basic_see.html, the current time will be returned:
Var http = require ("http ");
http.createServer(function(request, response){
response.writeHead(200, { "Content-Type": "text/event-stream" });
setInterval(function(){
var content = "data:" +
new Date().toISOString() + "\n\n";
response.write(content);
}, 1000);
}).listen(1234);
To improve the function, if we use Node. js to return HTML, the code is datepush. js:
var http = require("http"), fs = require("fs");
var port = parseInt( process.argv[2] || 1234 );
http.createServer(function(request, response){
console.log("Client connected:" + request.url);
if(request.url!="/sse"){
fs.readFile("basic_sse.html", function(err,file){
response.writeHead(200, { 'Content-Type': 'text/html' });
var s = file.toString(); //file is a buffer
s = s.replace("basic_sse.php","sse");
response.end(s);
});
return;
}
//Below is to handle SSE request. It never returns.
response.writeHead(200, { "Content-Type": "text/event-stream" });
var timer = setInterval(function(){
var content = "data:" + new Date().toISOString() + "\n\n";
var b = response.write(content);
if(!b)console.log("Data got queued in memory (content=" + content + ")");
else console.log("Flushed! (content=" + 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);
On the console, run node datepush2.js and access http: // 127.0.0.1: 1234/sse2 in the browser. The effect is as follows:
If (typeof (EventSource )! = "Undefined "){
// Yes! Server-sent events support!
}
else{
// Sorry! No server-sent events support in our system
}
Current browser support: