代码拉取完成,页面将自动刷新
const express = require('express');
const webSocketStream = require('websocket-stream/stream');
const expressWebSocket = require('express-ws');
const { v4: uuidv4 } = require('uuid')
// 客户端连接管理
const rtspConnectionsCache={}
// 代理客户端管理
const proxyAgentCache={}
/**
* 创建网络服务器
*/
function createServer() {
const app = express();
expressWebSocket(app, null, {
perMessageDeflate: true
});
// web rtsp request url
app.ws('/rtsp/', handlerRtsp);
// proxy agent client connect
app.ws('/proxy/', handlerProxy);
// push server stream
app.ws('/push/', handlerPush);
app.get('/', (req, response) => {
response.send('rtsp proxy');
});
var server = app.listen(8100,'0.0.0.0', () => {
const host =server.address().address
const port =server.address().port
console.log('started at http://%s:%s',host,port);
});
}
/**
* 处理请求连接
* @param {*} ws
* @param {*} req
*/
function handlerRtsp(ws, req){
const stream = webSocketStream(ws, {
binary: true,
browserBufferTimeout: 1000000
}, {
browserBufferTimeout: 1000000
});
const rtsp = new Buffer(req.query.url, 'base64').toString();
console.log('handler rtsp request')
const connectId = uuidv4()
rtspConnectionsCache[connectId]=stream
stream.on('close',()=>{
console.log('close rtsp connect for:',connectId,rtsp)
rtspConnectionsCache[connectId]=undefined
})
console.log('rtsp connect add cahced')
const proxyId = req.query.proxyId
const proxyClientStream =proxyAgentCache[proxyId]
if(!proxyClientStream){
ws.close()
}
const msg={
action:'connected',
connectId,
payload:{
rtsp
}
}
console.log('send msg',msg)
proxyClientStream.write(JSON.stringify(msg))
}
/**
* 处理网络连接
* @param {*} ws
* @param {*} req
*/
function handlerProxy(ws,req){
const stream = webSocketStream(ws, {
binary: false,
});
const proxyId = req.query.proxyId
proxyAgentCache[proxyId]=stream
console.log('add proxy agent into cache proxyId:',proxyId)
stream.on('close',()=>{
// 移除proxy id
console.log('remove proxyId from cache:',proxyId)
proxyAgentCache[proxyId]=undefined
})
}
/**
* handle push rtsp stream
* @param {*} ws
* @param {*} req
*/
function handlerPush(ws,req){
console.log('received push data')
const stream = webSocketStream(ws, {
binary: true,
browserBufferTimeout: 1000000
}, {
browserBufferTimeout: 1000000
});
const connectId = req.query.connectId
const connectStream = rtspConnectionsCache[connectId]
console.log("pipe to connectId",connectId)
if(!connectStream){
ws.close()
}
connectStream.on('close',()=>{
console.log('close rtsp push stream')
stream.end()
})
connectStream.on('error',()=>{
console.log('close rtsp push stream')
ws.close()
})
stream.pipe(connectStream)
}
createServer()
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。