要实现不需要端口转发和控制台应用程序的RTSP摄像头P2P连接,可以使用WebRTC技术。WebRTC(Web Real-Time Communication)是一个支持浏览器之间实时音视频通信的开放标准。以下是一个示例解决方案:
RTSP P2P Connection
由于RTSP摄像头的实际连接需要后端来处理,可以使用Node.js和WebRTC库webrtc-native来实现。
const http = require('http');
const WebSocket = require('ws');
const { RTCPeerConnection, RTCSessionDescription } = require('wrtc');
const wss = new WebSocket.Server({ port: 8080 });
wss.on('connection', function connection(ws) {
var peerConnection = new RTCPeerConnection();
// 接收到Offer并设置为远程描述
ws.on('message', function incoming(message) {
var offerSdp = JSON.parse(message).sdp;
peerConnection.setRemoteDescription(new RTCSessionDescription({ type: 'offer', sdp: offerSdp }));
// 创建Answer并发送给对方
peerConnection.createAnswer()
.then(function (answer) {
return peerConnection.setLocalDescription(answer);
})
.then(function () {
// 将answer发送给对方
var answerSdp = peerConnection.localDescription.sdp;
ws.send(JSON.stringify({ sdp: answerSdp }));
})
.catch(function (error) {
console.log('createAnswer error: ', error);
});
});
// 接收到ICE候选者并添加至PeerConnection
ws.on('message', function incoming(message) {
var candidate = JSON.parse(message).candidate;
peerConnection.addIceCandidate(candidate);
});
// 发送候选者到对方
peerConnection.onicecandidate = function (event) {
if (event.candidate) {
ws.send(JSON.stringify({ candidate: event.candidate }));
}
};
// 发送远程视频流到对方
peerConnection.ontrack