zhibo/live-streaming/server/routes/srs.js

93 lines
2.6 KiB
JavaScript
Raw Permalink 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.

const express = require('express');
const router = express.Router();
const roomStore = require('../store/roomStore');
const http = require('http');
// Java 后端地址 (host.docker.internal 用于从 Docker 容器访问宿主机)
const JAVA_BACKEND_HOST = process.env.JAVA_BACKEND_HOST || 'host.docker.internal';
const JAVA_BACKEND_PORT = process.env.JAVA_BACKEND_PORT || 8081;
// 转发到 Java 后端
function forwardToJava(path, data) {
const postData = JSON.stringify(data);
const options = {
hostname: JAVA_BACKEND_HOST,
port: JAVA_BACKEND_PORT,
path: path,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
},
timeout: 5000
};
const req = http.request(options, (res) => {
console.log(`[SRS->Java] ${path} 响应状态: ${res.statusCode}`);
});
req.on('error', (e) => {
console.error(`[SRS->Java] ${path} 转发失败: ${e.message}`);
});
req.on('timeout', () => {
console.error(`[SRS->Java] ${path} 转发超时`);
req.destroy();
});
req.write(postData);
req.end();
}
// POST /api/srs/on_publish - 推流开始回调
router.post('/on_publish', (req, res) => {
const { app, stream } = req.body;
console.log(`[SRS] 推流开始: app=${app}, stream=${stream}`);
// 更新内存存储
const room = roomStore.setLiveStatus(stream, true);
if (room) {
console.log(`[SRS] 房间 "${room.title}" 开始直播`);
} else {
console.log(`[SRS] 未找到对应房间streamKey=${stream}`);
}
// 转发到 Java 后端更新数据库
forwardToJava('/api/front/live/srs/on_publish', { stream });
// SRS 要求返回 code: 0 表示成功
res.json({ code: 0 });
});
// POST /api/srs/on_unpublish - 推流结束回调
router.post('/on_unpublish', (req, res) => {
const { app, stream } = req.body;
console.log(`[SRS] 推流结束: app=${app}, stream=${stream}`);
// 暂时禁用自动关闭直播,改为手动控制
// 这样可以避免网络波动导致直播状态被误重置
// const room = roomStore.setLiveStatus(stream, false);
// forwardToJava('/api/front/live/srs/on_unpublish', { stream });
res.json({ code: 0 });
});
// POST /api/srs/on_play - 观看回调 (可选)
router.post('/on_play', (req, res) => {
const { app, stream } = req.body;
console.log(`[SRS] 观众进入: app=${app}, stream=${stream}`);
res.json({ code: 0 });
});
// POST /api/srs/on_stop - 停止观看回调 (可选)
router.post('/on_stop', (req, res) => {
const { app, stream } = req.body;
console.log(`[SRS] 观众离开: app=${app}, stream=${stream}`);
res.json({ code: 0 });
});
module.exports = router;