SSE (Server-sent Events)

372 阅读1分钟

什么是SSE

服务器发送事件(Server-sent Events)是基于 WebSocket 协议的一种服务器向客户端发送事件和数据的单向通讯。 HTML5 服务器发送事件(server-sent event)允许网页获得来自服务器的更新。 说人话就是类似于WebSocket但是只能由服务端往客户端发消息的一种长连接,实质上是一个没有结束的长连接

  • 前端代码(用于接收数据)
	//前端代码
	var source=new EventSource("http:localhost:8000/sse");
	source.onmessage=function(event){
    		document.getElementById("result").innerHTML+=event.data + "<br>";
    	};
  • 后端代码(用于发送数据)
//新建app.js
const app = require('express')();
const http = require("http");

app.get('/sse', (req, res) => {
 res.writeHead(200, {
   "Content-Type": "text/event-stream;charset=utf-8",
   "Cache-Control": "no-cache",
   "Connection": "keep-alive",
   "Access-Control-Allow-Origin": '*',
 })
  res.write(`连接成功!\n\n`);
 
 //每秒钟往客户端发一次时间戳
 setInterval(function(){
  res.write(`${new Date()}\n\n`);
 },1000);


   //客户端关闭之后
 res.on("close", function () {
   console.log('连接断开')
   }
 );
})


//开放端口
http.createServer(app).listen(8000);
  • 试验步骤
    • 1.命令行敲 npm init

    • 1.1 npm i -D express

    • 1.2 node app.js

    • 2.浏览器输入 http://localhost:8000/sse 就可以看到效果了

说明:客户端代码可以在页面的JS里边写入,用于监听,挺有意思的一个知识点