You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
|
|
|
|
|
|
|
|
|
|
|
const express = require('express'); //引用框架
|
|
|
|
|
|
const moment = require("moment");
|
|
|
|
|
|
const app = express(); //创建服务
|
|
|
|
|
|
const port = 8088; //项目启动端口
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
// 处理跨域的插件
|
|
|
|
|
|
const cors = require('cors')
|
|
|
|
|
|
const moment = require("moment");
|
|
|
|
|
|
// 使用跨域插件
|
|
|
|
|
|
app.use(cors())
|
|
|
|
|
|
|
|
|
|
|
|
app.use(express.static('public'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
app.get("/sse",(req,res) => {
|
|
|
|
|
|
res.set({
|
|
|
|
|
|
'Content-Type': 'text/event-stream;charset=utf-8', //设定数据类型,设置 SSE 响应类型(告诉客户端响应类型,这是一个SSE事件流)
|
|
|
|
|
|
'Cache-Control': 'no-cache',// 长链接拒绝缓存,告诉浏览器不要直接使用缓存中的资源,而是应该向服务器发送请求来检查该资源是否有更新。
|
|
|
|
|
|
'Access-Control-Allow-Origin': '*',// 告诉浏览器,来自任何源的请求都可以被接受并访问该资源。可以跨域
|
|
|
|
|
|
'Connection': 'keep-alive'//设置长链接,用于控制网络连接的持久性。
|
|
|
|
|
|
});
|
|
|
|
|
|
console.log("进入到长连接了")
|
|
|
|
|
|
//持续返回数据
|
|
|
|
|
|
setInterval(() => {
|
|
|
|
|
|
console.log("正在持续返回数据中ing")
|
|
|
|
|
|
const date = new Date();
|
|
|
|
|
|
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
|
|
|
|
|
|
console.log(formattedDate);
|
|
|
|
|
|
//const data = { message: `Current time is ${new Date().toLocaleTimeString()}`};
|
|
|
|
|
|
const data = { message: `Current time is ${formattedDate}`};
|
|
|
|
|
|
res.write(`data: ${JSON.stringify(data)}\n\n`);
|
|
|
|
|
|
}, 1000);
|
|
|
|
|
|
})
|
|
|
|
|
|
//创建项目
|
|
|
|
|
|
app.listen(port, () => {
|
|
|
|
|
|
console.log(`项目启动成功-http://localhost:${port}`)
|
|
|
|
|
|
})
|