Files
sse-server/lib/sse.js
2025-07-02 21:05:33 +08:00

41 lines
1.3 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* @file 处理SSE请求
* @author Yk <yk_9001@icloud.com>
* @createdAt 2025-07-01
* @lastModifiedAt 2025-07-01
* @description 维护链接的客户端
*/
// 引入客户端管理模块,用于维护连接的客户端
const clients = require('./clients');
const timestamp = require('../utils/timeFormatter');
/**
* 设置 SSEServer-Sent Events响应头确保客户端能够正确接收事件流
* @param {Object} res - HTTP 响应对象
*/
function setupSSEHeaders(res) {
res.setHeader('Content-Type', 'text/event-stream'); // 指定内容类型为事件流
res.setHeader('Cache-Control', 'no-cache'); // 禁止缓存
res.setHeader('Connection', 'keep-alive'); // 保持长连接
res.flushHeaders(); // 立即发送响应头
}
/**
* 发送心跳事件给所有连接的客户端,用于保持连接活跃并传递服务器时间
* @returns {void}
*/
function sendHeartbeat() {
const data = {
event: 'heartbeat', // 事件类型为 heartbeat
time: timestamp.formatTime() // 当前时间的 ISO 字符串格式
};
return clients.broadcast(data); // 广播给所有连接的客户端
}
// 导出函数,供其他模块使用
module.exports = {
setupSSEHeaders,
sendHeartbeat
};