加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
proxy-server.js 3.08 KB
一键复制 编辑 原始数据 按行查看 历史
liangyali 提交于 2024-10-26 04:24 . fix
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()
Loading...
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化