zhibo/live-streaming/server/index.js

85 lines
2.6 KiB
JavaScript

require('dotenv').config();
const express = require('express');
const cors = require('cors');
const NodeMediaServer = require('node-media-server');
const roomsRouter = require('./routes/rooms');
const srsRouter = require('./routes/srs');
const errorHandler = require('./middleware/errorHandler');
const roomStore = require('./store/roomStore');
const app = express();
const PORT = process.env.PORT || 3001;
const startMediaServer = () => {
const host = process.env.SRS_HOST || 'localhost';
const rtmpPort = Number(process.env.SRS_RTMP_PORT || 1935);
const httpPort = Number(process.env.SRS_HTTP_PORT || 8080);
try {
const nms = new NodeMediaServer({
rtmp: {
port: rtmpPort,
chunk_size: 60000,
gop_cache: true,
ping: 30,
ping_timeout: 60
},
http: {
port: httpPort,
allow_origin: '*'
}
});
nms.on('prePublish', (id, streamPath) => {
const parts = String(streamPath || '').split('/').filter(Boolean);
const streamKey = parts[1];
if (streamKey) roomStore.setLiveStatus(streamKey, true);
});
nms.on('donePublish', (id, streamPath) => {
const parts = String(streamPath || '').split('/').filter(Boolean);
const streamKey = parts[1];
if (streamKey) roomStore.setLiveStatus(streamKey, false);
});
nms.run();
console.log(`Media Server RTMP: rtmp://${host}:${rtmpPort}/live (Stream Key = streamKey)`);
console.log(`Media Server HTTP-FLV: http://${host}:${httpPort}/live/{streamKey}.flv`);
} catch (e) {
console.error('[Media Server] Failed to start embedded media server:', e.message);
console.error('[Media Server] If ports 1935/8080 are in use, stop the occupying process or change SRS_RTMP_PORT/SRS_HTTP_PORT.');
}
};
startMediaServer();
// 中间件
app.use(cors({
origin: process.env.CLIENT_URL || 'http://localhost:3000',
credentials: true
}));
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
// 路由
app.use('/api/rooms', roomsRouter);
app.use('/api/srs', srsRouter);
// 健康检查
app.get('/health', (req, res) => {
res.json({ status: 'ok', timestamp: new Date().toISOString() });
});
// 错误处理
app.use(errorHandler);
// 启动服务
app.listen(PORT, () => {
console.log(`API 服务运行在 http://localhost:${PORT}`);
console.log(`SRS RTMP: rtmp://${process.env.SRS_HOST || 'localhost'}:${process.env.SRS_RTMP_PORT || 1935}/live/{streamKey}`);
console.log(`SRS HTTP: http://${process.env.SRS_HOST || 'localhost'}:${process.env.SRS_HTTP_PORT || 8080}/live/{streamKey}.flv`);
});
module.exports = app;