sse,html测试

main
wenfei 7 months ago
parent 97e1a6202e
commit 9db91c2c10

5
.gitignore vendored

@ -24,10 +24,11 @@ server_demo/.idea/*
/server_demo/node_modules/* /server_demo/node_modules/*
server_demo/node_modules/* server_demo/node_modules/*
/sse_demo/node_modules/*
sse_demo/node_modules/*
/server_demo/.idea
server_demo/.idea
# Diagnostic reports (https://nodejs.org/api/report.html) # Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

@ -6,7 +6,15 @@ const router = express.Router()
const oracledb = require('oracledb'); const oracledb = require('oracledb');
const connectionString = "system/452131wW@192.168.3.29:1521/orcl"; // 替换为实际的用户名、密码、主机名、端口号和数据库名 const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'Skyinno251,',
database: 'appserver',
connectionLimit: 10 // 连接池最大连接数
});
// 设置数据库连接参数 // 设置数据库连接参数
const config = { const config = {
@ -79,4 +87,32 @@ router.delete('/delete', (req, res) => {
}) })
}) })
// 在这里挂载对应的路由
router.get('/getUser', (req, res) => {
pool.query('SELECT * FROM user', (err, rows) => {
if (err) {
console.error('Error querying database:', err);
res.status(500).send('Internal Server Error');
} else {
console.log(rows)
res.send({
status: 1,
msg: 'POST请求成功',
data: rows
})
//res.json(rows);
}
});
pool.getConnection((err, connection) => {
if (err) throw err;
connection.query('SELECT * FROM time_now', (error, results, fields) => {
connection.release(); // 释放连接
if (error) throw error;
console.log(results);
});
});
})
module.exports = router module.exports = router

@ -0,0 +1,32 @@
const mysql = require('mysql2');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'Skyinno251,',
database : 'appserver'
});
connection.connect((err) => {
if (err) {
console.error('连接失败: ' + err.stack);
return;
}
console.log('连接成功线程ID: ' + connection.threadId);
//
var sql = 'SELECT * FROM temperature where id < 50';
//查
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
connection.end();
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(result);
console.log('------------------------------------------------------------\n\n');
connection.end();
});
});

@ -0,0 +1,19 @@
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'Skyinno251,',
database: 'appserver',
connectionLimit: 10 // 连接池最大连接数
});
pool.query('SELECT * FROM user', (err, rows) => {
if (err) {
console.error('Error querying database:', err);
//res.status(500).send('Internal Server Error');
} else {
//res.json(rows);
}
});

@ -0,0 +1,35 @@
const oracledb = require('oracledb');
// 设置数据库连接参数
const config = {
user: 'system',
password: '452131wW',
connectString : "192.168.3.29:1521/orcl" // 或者直接使用 'hostname:port/sid'
};
async function run() {
let connection;
try {
// 获取数据库连接
connection = await oracledb.getConnection(config);
console.log('Connection established.');
// 执行查询
const result = await connection.execute('SELECT * FROM TYPE');
console.log(result.rows); // 输出查询结果
} catch (err) {
console.error(err);
} finally {
if (connection) {
// 关闭数据库连接
try {
await connection.close();
console.log('Connection closed.');
} catch (err) {
console.error(err);
}
}
}
}

@ -11,6 +11,7 @@
"dependencies": { "dependencies": {
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^5.1.0", "express": "^5.1.0",
"mysql2": "^3.14.1",
"nodemon": "^3.1.10", "nodemon": "^3.1.10",
"oracledb": "^5.5.0" "oracledb": "^5.5.0"
} }
@ -41,6 +42,15 @@
"node": ">= 8" "node": ">= 8"
} }
}, },
"node_modules/aws-ssl-profiles": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz",
"integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==",
"license": "MIT",
"engines": {
"node": ">= 6.0.0"
}
},
"node_modules/balanced-match": { "node_modules/balanced-match": {
"version": "1.0.2", "version": "1.0.2",
"resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz",
@ -238,6 +248,15 @@
} }
} }
}, },
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
"integrity": "sha512-HVQE3AAb/pxF8fQAoiqpvg9i3evqug3hoiwakOyZAwJm+6vZehbkYXZ0l4JxS+I3QxM97v5aaRNhj8v5oBhekw==",
"license": "Apache-2.0",
"engines": {
"node": ">=0.10"
}
},
"node_modules/depd": { "node_modules/depd": {
"version": "2.0.0", "version": "2.0.0",
"resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz", "resolved": "https://registry.npmjs.org/depd/-/depd-2.0.0.tgz",
@ -433,6 +452,15 @@
"url": "https://github.com/sponsors/ljharb" "url": "https://github.com/sponsors/ljharb"
} }
}, },
"node_modules/generate-function": {
"version": "2.3.1",
"resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz",
"integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==",
"license": "MIT",
"dependencies": {
"is-property": "^1.0.2"
}
},
"node_modules/get-intrinsic": { "node_modules/get-intrinsic": {
"version": "1.3.0", "version": "1.3.0",
"resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz", "resolved": "https://registry.npmjs.org/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
@ -624,6 +652,42 @@
"integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==", "integrity": "sha512-hvpoI6korhJMnej285dSg6nu1+e6uxs7zG3BYAm5byqDsgJNWwxzM6z6iZiAgQR4TJ30JmBTOwqZUw3WlyH3AQ==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/is-property": {
"version": "1.0.2",
"resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz",
"integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==",
"license": "MIT"
},
"node_modules/long": {
"version": "5.3.2",
"resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz",
"integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==",
"license": "Apache-2.0"
},
"node_modules/lru-cache": {
"version": "7.18.3",
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-7.18.3.tgz",
"integrity": "sha512-jumlc0BIUrS3qJGgIkWZsyfAM7NCWiBcCDhnd+3NNM5KbBmLTgHVfWBcg6W+rLUsIpzpERPsvwUP7CckAQSOoA==",
"license": "ISC",
"engines": {
"node": ">=12"
}
},
"node_modules/lru.min": {
"version": "1.1.2",
"resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.2.tgz",
"integrity": "sha512-Nv9KddBcQSlQopmBHXSsZVY5xsdlZkdH/Iey0BlcBYggMd4two7cZnKOK9vmy3nY0O5RGH99z1PCeTpPqszUYg==",
"license": "MIT",
"engines": {
"bun": ">=1.0.0",
"deno": ">=1.30.0",
"node": ">=8.0.0"
},
"funding": {
"type": "github",
"url": "https://github.com/sponsors/wellwelwel"
}
},
"node_modules/math-intrinsics": { "node_modules/math-intrinsics": {
"version": "1.1.0", "version": "1.1.0",
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz", "resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
@ -693,6 +757,38 @@
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
"license": "MIT" "license": "MIT"
}, },
"node_modules/mysql2": {
"version": "3.14.1",
"resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.14.1.tgz",
"integrity": "sha512-7ytuPQJjQB8TNAYX/H2yhL+iQOnIBjAMam361R7UAL0lOVXWjtdrmoL9HYKqKoLp/8UUTRcvo1QPvK9KL7wA8w==",
"license": "MIT",
"dependencies": {
"aws-ssl-profiles": "^1.1.1",
"denque": "^2.1.0",
"generate-function": "^2.3.1",
"iconv-lite": "^0.6.3",
"long": "^5.2.1",
"lru.min": "^1.0.0",
"named-placeholders": "^1.1.3",
"seq-queue": "^0.0.5",
"sqlstring": "^2.3.2"
},
"engines": {
"node": ">= 8.0"
}
},
"node_modules/named-placeholders": {
"version": "1.1.3",
"resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.3.tgz",
"integrity": "sha512-eLoBxg6wE/rZkJPhU/xRX1WTpkFEwDJEN96oxFrTsqBdbT5ec295Q+CoHrL9IT0DipqKhmGcaZmwOt8OON5x1w==",
"license": "MIT",
"dependencies": {
"lru-cache": "^7.14.1"
},
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/negotiator": { "node_modules/negotiator": {
"version": "1.0.0", "version": "1.0.0",
"resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz", "resolved": "https://registry.npmjs.org/negotiator/-/negotiator-1.0.0.tgz",
@ -967,6 +1063,11 @@
"node": ">= 18" "node": ">= 18"
} }
}, },
"node_modules/seq-queue": {
"version": "0.0.5",
"resolved": "https://registry.npmjs.org/seq-queue/-/seq-queue-0.0.5.tgz",
"integrity": "sha512-hr3Wtp/GZIc/6DAGPDcV4/9WoZhjrkXsi5B/07QgX8tsdc6ilr7BFM6PM6rbdAX1kFSDYeZGLipIZZKyQP0O5Q=="
},
"node_modules/serve-static": { "node_modules/serve-static": {
"version": "2.2.0", "version": "2.2.0",
"resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz", "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-2.2.0.tgz",
@ -1072,6 +1173,15 @@
"node": ">=10" "node": ">=10"
} }
}, },
"node_modules/sqlstring": {
"version": "2.3.3",
"resolved": "https://registry.npmjs.org/sqlstring/-/sqlstring-2.3.3.tgz",
"integrity": "sha512-qC9iz2FlN7DQl3+wjwn3802RTyjCx7sDvfQEXchwa6CWOx07/WVfh91gBmQ9fahw8snwGEWU3xGzOt4tFyHLxg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/statuses": { "node_modules/statuses": {
"version": "2.0.1", "version": "2.0.1",
"resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz",

@ -2,11 +2,10 @@
"name": "server_demo", "name": "server_demo",
"version": "1.0.0", "version": "1.0.0",
"description": "", "description": "",
"main": "index.js", "main": "server.js",
"scripts": { "scripts": {
"test": "echo \"Error: no test specified\" && exit 1", "test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon server.js", "start": "nodemon --ext js,html,css server.js"
"start1": "nodemon --ext js,html,css server.js"
}, },
"keywords": [], "keywords": [],
"author": "", "author": "",
@ -14,6 +13,7 @@
"dependencies": { "dependencies": {
"cors": "^2.8.5", "cors": "^2.8.5",
"express": "^5.1.0", "express": "^5.1.0",
"mysql2": "^3.14.1",
"nodemon": "^3.1.10", "nodemon": "^3.1.10",
"oracledb": "^5.5.0" "oracledb": "^5.5.0"
} }

@ -0,0 +1,260 @@
//16.apiRouter.js
const express = require('express')
const bodyParser = require('body-parser');
const router = express.Router()
const fs = require("fs");
const mysql = require('mysql2');
const moment = require("moment");
const util = require('util');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'Skyinno251,',
database: 'appserver',
multipleStatements: true, // 允许执行多条语句,(高并发方式)
connectionLimit: 10 // 连接池最大连接数
});
// 在这里挂载对应的路由
router.get('/get', (req, res) => {
// 通过 req.query 获取客户端发送到服务器的数据(查询字符串)
const query = req.query
run().then(r => {console.log("调用oracle")})
// 调用 res.send() 方法,向客户端响应处理的结果
res.send({
status: 0,// 0 表示处理成功1 表示处理失败
msg: 'GRT请求成功', // 状态的描述
data: query// 需要响应给客户端的数据
})
})
router.post('/addTimeNow', (req, res) => {
// 通过 req.body 获取请求体中包含的 url-encoded 格式的数据
const body = req.body
res.send({
status: 1,
msg: 'POST请求成功',
data: body
})
})
// 新增用户 POST 请求处理程序
router.post('/addUserNow', (req, res) => {
const date = new Date();
const formattedDate = moment(date).format('YYYY-MM-DD HH:mm:ss');
console.log(formattedDate);
const { name, age } = req.body; // 从请求体中获取数据
if (name == undefined||name == ''||name == null) {
res.status(500).json({ error: 'name not null' });
return
}
if (age == undefined||age == ''||age == null) {
res.status(500).json({ error: 'age not null' });
return
}
const values = [name, age, date];
const insertSql = `INSERT INTO user_now (name, age,create_time) VALUES (?, ?, ?)`;
pool.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,
});
});
});
router.delete('/delete', (req, res) => {
res.send({
status: 0,
msg: 'DELETE请求成功',
})
})
// 获取用户详情 3
router.get('/user/:username', (req, res) => {
const { username } = req.params;
if (username == undefined||username == ''||username == null) {
res.status(500).json({ error: 'username not null' });
return
}
const values =[username];
let query = 'SELECT * FROM user WHERE username = ?';
pool.query(query,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?results[0]:{},
});
});
});
router.get('/user', (req, res) => {
const { username, name } = req.query;
//const values =[username, name];
let query = 'SELECT * FROM user';
// 构建查询条件
const params = [];
if (name !== undefined&&name !== ''&&name !== null) {
query += ' WHERE name = ?';
params.push(name);
}
if (username !== undefined&&username !== ''&&username !== null) {
query += params.length ? ' AND' : ' WHERE';
query += ' username = ?';
params.push(username);
}
// 查询数据库并返回数据
pool.query(query,params,(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,
});
});
});
router.put('/userPut', (req, res) => {
// console.log(req.body);
const { name, age ,id} = req.body; // 从请求体中获取数据
if (id == undefined||id == ''||id == null) {
res.status(500).json({ error: 'id not null' });
return
}
if (name == undefined||name == ''||name == null) {
res.status(500).json({ error: 'name not null' });
return
}
if (age == undefined||age == ''||age == null) {
res.status(500).json({ error: 'age not null' });
return
}
const values = [name, age, id];
// 准备 SQL 插入语句
const sql = "UPDATE user_now SET name = ?, age = ? WHERE id = ?";
pool.query(sql, values, (err, results) => {
// console.log(err,'err');
// console.log(results,'results');
if (err) {
console.error('Error querying database:', err);
res.status(500).json({ error: 'Internal server error' });
return;
}
res.json({
code:'200',
data:results,
});
});
});
// 删除用户数据 DELETE请求处理程序
router.delete('/userDel/:id', (req, res) => {
// const {id} = req.body; // 从请求体中获取数据
const id = req.params.id;
if (id == undefined||id == ''||id == null) {
res.status(500).json({ error: 'id not null' });
return
}
// console.log(id,'id');
const values = [id];
const sql = "DELETE FROM time_now WHERE id = ?";
pool.query(sql, values, (err, results) => {
// console.log(err,'err');
// console.log(results,'results');
if (err) {
console.error('Error querying database:', err);
res.status(500).json({ error: 'Internal server error' });
return;
}
res.json({
code:'200',
data:results,
});
});
});
router.get('/process_get', function (req, res) {
// 输出 JSON 格式
var response = {
"first_name":req.query.first_name,
"last_name":req.query.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
// 创建 application/x-www-form-urlencoded 编码解析
const urlencodedParser = bodyParser.urlencoded({ extended: false })
router.post('/process_post', urlencodedParser, function (req, res) {
// 输出 JSON 格式
var response = {
"first_name":req.body.first_name,
"last_name":req.body.last_name
};
console.log(response);
res.end(JSON.stringify(response));
})
router.post('/file_upload', function (req, res) {
console.log(req.files[0]); // 上传的文件信息
const des_file = "/Users/admin/tmp/" + req.files[0].originalname;
fs.readFile( req.files[0].path, function (err, data) {
fs.writeFile(des_file, data, function (err) {
if( err ){
console.log( err );
}else{
response = {
message:'File uploaded successfully',
filename:req.files[0].originalname
};
}
console.log( response );
res.end( JSON.stringify( response ) );
});
});
})
router.get('/getCookies', function(req, res) {
console.log("Cookies: " + util.inspect(req.cookies));
res.end( JSON.stringify( util.inspect(req.cookies) ) );
})
module.exports = router

@ -0,0 +1,55 @@
// app.js
const express=require("express");
const path=require("path")
// 处理跨域的插件
const cors = require('cors')
// SSE相关信息路由
const sseInfoRouter = require('./routes/sse/infoPush');
const cookieParser = require('cookie-parser')
const app= express();
const bodyParser = require('body-parser');
const multer = require('multer');
app.use(bodyParser.urlencoded({ extended: false }));
app.use(multer({ dest: '/tmp/'}).array('image'));
app.use(cookieParser())
// 使用跨域插件
app.use(cors())
// app.use('/public', express.static('public'))
app.use(express.static('public'))
app.use(express.static('/tmp/'))
// app.use('/public', express.static('public'));
app.get('/get.html', function (req, res) {
res.sendFile( __dirname + "/" + "get.html" );
})
console.log(__dirname)
app.use('/sse', sseInfoRouter);
// 配置解析表单数据的中间件
app.use(express.urlencoded({ extended: false }))
// 导入路由模块
const apiRouter = require('./apiRouter.js')
// 把路由模块,注册到 app 上
app.use('/api', apiRouter)
//端口
app.listen(3000,function () {
console.log("127.0.0.1:3000")
});

@ -0,0 +1,32 @@
const mysql = require('mysql2');
const connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : 'Skyinno251,',
database : 'appserver'
});
connection.connect((err) => {
if (err) {
console.error('连接失败: ' + err.stack);
return;
}
console.log('连接成功线程ID: ' + connection.threadId);
//
var sql = 'SELECT * FROM temperature where id < 50';
//查
connection.query(sql,function (err, result) {
if(err){
console.log('[SELECT ERROR] - ',err.message);
connection.end();
return;
}
console.log('--------------------------SELECT----------------------------');
console.log(result);
console.log('------------------------------------------------------------\n\n');
connection.end();
});
});

@ -0,0 +1,18 @@
const mysql = require('mysql2');
const pool = mysql.createPool({
host: 'localhost',
user: 'root',
password: 'Skyinno251,',
database: 'appserver',
connectionLimit: 10 // 连接池最大连接数
});
pool.query('SELECT * FROM user', (err, rows) => {
if (err) {
console.error('Error querying database:', err);
//res.status(500).send('Internal Server Error');
} else {
//res.json(rows);
}
});

File diff suppressed because it is too large Load Diff

@ -0,0 +1,26 @@
{
"name": "sse_demo",
"version": "1.0.0",
"description": "sse",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "nodemon --ext js,html,css index.js",
"startServer": "nodemon server.js"
},
"keywords": [
"sse"
],
"author": "wenfei",
"license": "ISC",
"dependencies": {
"body-parser": "^2.2.0",
"cookie-parser": "^1.4.7",
"cors": "^2.8.5",
"express": "^5.1.0",
"moment": "^2.30.1",
"multer": "^1.4.5-lts.2",
"mysql2": "^3.14.1",
"nodemon": "^3.1.10"
}
}

@ -0,0 +1,14 @@
<html>
<head>
<title>文件上传表单</title>
</head>
<body>
<h3>文件上传:</h3>
选择一个文件上传: <br />
<form action="/api/file_upload" method="post" enctype="multipart/form-data">
<input type="file" name="image" size="50" />
<br />
<input type="submit" value="上传文件" />
</form>
</body>
</html>

@ -0,0 +1,10 @@
<html>
<body>
<form action="/api/process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>

@ -0,0 +1,77 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title></head>
<body>
<ul id="ul"></ul>
</body>
<script>
//生成li元素
function createLi(data) {
let li = document.createElement("li");
li.innerHTML = String(data.message);
return li;
}
//判断当前浏览器是否支持SSE
let source = ''
if (!!window.EventSource) {
source = new EventSource('http://127.0.0.1:3000/sse/ai/question/push?title=请你介绍一下SSE');
if (source.readyState === 0) {
//sseObj.readyState === EventSource.CONNECTING 也可以判断正在连接服务器
console.log('0:"正在连接服务器...');
}
} else {
throw new Error("当前浏览器不支持SSE")
}
//对于建立链接的监听
source.onopen = function (event) {
console.log(source.readyState);
console.log("长连接打开");
if (source.readyState === 1) {
// sseObj.readyState === EventSource.OPEN 也可以判断连接成功
let data = `SSE 连接成功,状态${source.readyState}, 对象${event}`;
console.log(data);
console.log("1:SSE 连接成功");
}
};
//对服务端消息的监听
source.onmessage =
function (event) {
console.log(JSON.parse(event.data));
console.log("收到长连接信息");
let li = createLi(JSON.parse(event.data));
document.getElementById("ul").appendChild(li)
};
// 接收消息,这个事件需要和后端保持一致哈
// 后端的事件名称sseEvent
// source.addEventListener("sseEvent", function (event) {
// const data = JSON.parse(event.data);
// //如果最后推送的是 'contDnd',说明推送已经完了。此时关闭连接
// if (data.content === 'contDnd') {
// source.close();
// if (source.readyState === 2) {
// // sseObj.readyState === EventSource.CLOSED 也可以判断连接已经关闭
// console.log('2连接已经关闭。', source.readyState);
// }
// console.log("end");
// } else {
// let li = createLi(JSON.parse(data.content));
// document.getElementById("ul").appendChild(li)
// }
// console.log("这次消息推送的内容event:", data.content);
// });
//对断开链接的监听
source.onerror = function (event) {
console.log(source.readyState);
console.log("长连接中断");
};
</script>
</html>

@ -0,0 +1,100 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script>
export default {
data() {
return {
eventSource: null,
stateData: null,
list: [],
connectStatus: false,
};
},
created() {
},
methods: {
startConnectHandler() {
let url = "http://127.0.0.1:3000/sse/ai/question/push?title=请你介绍一下SSE";
// 表示与服务器建立连接的 URL。必填。
const sseObj = new EventSource(url);
this.eventSource = sseObj;
console.log('状态', sseObj, this.eventSource)
if (sseObj.readyState === 0) {
this.connectStatus = true
//sseObj.readyState === EventSource.CONNECTING 也可以判断正在连接服务器
console.log('0:"正在连接服务器...');
}
sseObj.onopen = (e) => {
if (sseObj.readyState === 1) {
// sseObj.readyState === EventSource.OPEN 也可以判断连接成功
let data = `SSE 连接成功,状态${sseObj.readyState}, 对象${e}`;
this.stateData = data;
console.log("1:SSE 连接成功");
}
};
// 接收消息,这个事件需要和后端保持一致哈
// 后端的事件名称sseEvent
sseObj.addEventListener("sseEvent", (event) => {
const data = JSON.parse(event.data);
//如果最后推送的是 'contDnd',说明推送已经完了。此时关闭连接
if (data.content === 'contDnd') {
this.endConnectHandler()
} else {
this.list.push(data.content);
}
console.log("这次消息推送的内容event:", data.content);
});
sseObj.onerror = (e) => {
console.log("error", e);
};
},
endConnectHandler() {
if (this.eventSource) {
this.connectStatus = false
this.eventSource.close();
if (this.eventSource.readyState === 2) {
// sseObj.readyState === EventSource.CLOSED 也可以判断连接已经关闭
console.log('2连接已经关闭。', this.eventSource, this.eventSource.readyState);
}
console.log("end");
}
},
},
};
</script>
<style scoped>
.chat-box {
padding-left: 20px;
padding-top: 20px;
}
button {
margin-right: 20px;
padding: 6px;
}
</style>
</head>
<body>
<template>
<div class="chat-box">
<button @click="startConnectHandler" :disabled="connectStatus">建立连接</button>
<button @click="endConnectHandler">关闭连接</button>
<h2>
<p>连接状态{{ this.eventSource && this.eventSource.readyState }}</p>
</h2>
<h2>下面就是返回来的数据</h2>
<div>
<div v-for="(item, index) in list" :key="index">
{{ item }}
</div>
</div>
</div>
</template>
</body>
</html>

@ -0,0 +1,10 @@
<html>
<body>
<form action="/api/process_post" method="POST">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name"><br/>
<input type="submit" value="Submit">
</form>
</body>
</html>

@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>SSE测试</title></head>
<body>
<ul id="ul"></ul>
</body>
<script>
//生成li元素
function createLi(data) {
let li = document.createElement("li");
li.innerHTML = String(data.message);
return li;
}
//判断当前浏览器是否支持SSE
let source = ''
if (!!window.EventSource) {
source = new EventSource('http://localhost:8088/sse/');
} else {
throw new Error("当前浏览器不支持SSE")
}
//对于建立链接的监听
source.onopen = function (event) {
console.log(source.readyState);
console.log("长连接打开");
};
//对服务端消息的监听
source.onmessage =
function (event) {
console.log(JSON.parse(event.data));
console.log("收到长连接信息");
let li = createLi(JSON.parse(event.data));
document.getElementById("ul").appendChild(li)
};
//对断开链接的监听
source.onerror = function (event) {
console.log(source.readyState);
console.log("长连接中断");
};
</script>
</html>

@ -0,0 +1,91 @@
// 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;

@ -0,0 +1,40 @@
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}`)
})

@ -0,0 +1,45 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title></head>
<body>
<ul id="ul"></ul>
</body>
<script>
//生成li元素
function createLi(data) {
let li = document.createElement("li");
li.innerHTML = String(data.message);
return li;
}
//判断当前浏览器是否支持SSE
let source = ''
if (!!window.EventSource) {
source = new EventSource('http://localhost:8088/sse/');
} else {
throw new Error("当前浏览器不支持SSE")
}
//对于建立链接的监听
source.onopen = function (event) {
console.log(source.readyState);
console.log("长连接打开");
};
//对服务端消息的监听
source.onmessage =
function (event) {
console.log(JSON.parse(event.data));
console.log("收到长连接信息");
let li = createLi(JSON.parse(event.data));
document.getElementById("ul").appendChild(li)
};
//对断开链接的监听
source.onerror = function (event) {
console.log(source.readyState);
console.log("长连接中断");
};
</script>
</html>
Loading…
Cancel
Save