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.

92 lines
3.1 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// routes/sse/infoPush.js 文件
const express = require("express");
const moment = require("moment");
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'Skyinno251,',
database: 'appserver',
connectionLimit: 10 // 连接池最大连接数
});
// const {oracleRun} = require("../../oracle");
const router = express.Router();
router.get("/ai/question/push", (req, res) => {
// 设置 SSE 响应类型(告诉客户端响应类型这是一个SSE事件流)
res.setHeader("Content-Type", "text/event-stream;charset=utf-8");
/**
* 告诉浏览器不要直接使用缓存中的资源,而是应该向服务器发送请求来检查该资源是否有更新。
* 确保用户获取到最新内容是非常有用尤其是在内容频繁更新的Web应用中。
* */
res.setHeader("Cache-Control", "no-cache");
// 用于控制网络连接的持久性。
res.setHeader("Connection", "keep-alive");
// 告诉浏览器,来自任何源的请求都可以被接受并访问该资源。可以跨域
res.setHeader("Access-Control-Allow-Origin", "*");
console.log("进入到长连接了")
let index = 0;
const timer = setInterval(() => {
const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate);
console.log("正在持续返回数据中ing")
// const data = { message: `Current time is ${new Date().toLocaleTimeString()}`};
const data = { message: `Current time is ${formattedDate}`};
res.write(`data: ${JSON.stringify(data)}\n\n`);
//res.write("data: " + JSON.stringify({ message: new Date().toLocaleTimeString()}) + "\n\n");
index++;
console.log(index)
const values = [date, formattedDate];
const insertSql = `INSERT INTO time_now (time, date_time) VALUES (?, ?)`;
pool.query(insertSql, values, (err, results) => {
if (err) {
console.error('Error internal database:', err);
res.status(500).json({ error: 'Internal server error' });
return;
}
console.log(results)
// res.json({
// code:'200',
// data:results,
// });
});
}, 5000);
// 当客户端点击关闭时,我们清除定时器,并且结束推送
req.on("close", () => {
clearInterval(timer);
res.end();
});
});
// // 新增用户 POST 请求处理程序
// app.post('/api/user', (req, res) => {
// const { name, age } = req.body; // 从请求体中获取数据
// const values = [name, age];
// const insertSql = `INSERT INTO user (name, age) VALUES (?, ?)`;
// connectionpool.query(insertSql, values, (err, results) => {
// if (err) {
// console.error('Error querying database:', err);
// res.status(500).json({ error: 'Internal server error' });
// return;
// }
// res.json({
// code:'200',
// data:results,
// });
// });
// });
module.exports = router;