初始化SSE服务端项目
This commit is contained in:
37
routes/push.js
Normal file
37
routes/push.js
Normal file
@ -0,0 +1,37 @@
|
||||
/**
|
||||
* @file SSE流路由处理器
|
||||
* @author Yk <yk_9001@icloud.com>
|
||||
* @createdAt 2025-07-01
|
||||
* @lastModifiedAt 2025-07-01
|
||||
* @description 处理SSE连接
|
||||
*/
|
||||
|
||||
const express = require('express');
|
||||
const clients = require('../lib/clients');
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
router.post('/', (req, res) => {
|
||||
const { message, clientId } = req.body;
|
||||
|
||||
if (!message) {
|
||||
return res.status(400).json({ error: 'Message is required' });
|
||||
}
|
||||
|
||||
const data = { message, time: new Date().toISOString() };
|
||||
|
||||
if (clientId) {
|
||||
const clientRes = clients.get(clientId);
|
||||
if (!clientRes) {
|
||||
return res.status(404).json({ error: 'Client not found' });
|
||||
}
|
||||
|
||||
clientRes.write(`data: ${JSON.stringify(data)}\n\n`);
|
||||
return res.json({ message: 'Message delivered', clientId });
|
||||
}
|
||||
|
||||
const count = clients.broadcast(data);
|
||||
return res.json({ message: 'Message broadcasted', clients: count });
|
||||
});
|
||||
|
||||
module.exports = router;
|
Reference in New Issue
Block a user