Firstly introduce the HTML5 API:
The EventSource
interface is web content's interface to server-sent events. An EventSource
instance opens a persistent connection to an HTTP server, which sends events in text/event-stream
format. The connection remains open until closed by calling EventSource.close()
.
Usage:
var evtSource = new EventSource("/data");//向服务器接收数据
Event API:
//receive server info
evtSource.onmessage = function (e) {
console.log(e.data);
}
//trigger by connect server success
evtSource.onopen = function () {
console.log("Server open")
}
//trigger by some err
evtSource.onerror = function () {
console.log("Error")
}
Example(Base on node):
var http=require("http"); var fs=require("fs"); http.createServer(function(req,res){ if(req.url=='/'){ fs.readFile("index.html",function(err,buf){ if(err){ res.end(404);return }else{ res.end(buf); } }); }else if(req.url=="/data"){ res.setHeader('Cache-control', 'no-cache'); res.setHeader('Content-Type', 'text/event-stream'); let i=0; while(i<1000){ console.log(i); res.write("data:" + new Date().toLocaleTimeString() + "\n\n" + "data:" + i + "\n\n");//这里必须为\n\n才能是数据流分开,同时事件流给前台只会是data属性,不能设置其他属性 i++; } } }).listen(3000)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> </head> <body> </body> <script src="https://cdn.bootcss.com/jquery/3.3.1/jquery.js"></script> <script> var evtSource = new EventSource('/data'); //收到服务器发生的事件时触发 evtSource.onmessage = function (e) { console.log(e.data); } //成功与服务器发生连接时触发 evtSource.onopen = function () { console.log("Server open") } //出现错误时触发 evtSource.onerror = function () { console.log("Error") } </script> </html>
AS follow result is: