Fix dangling webrtc connections (#8251)

* fix dangling webrtc connections

* Make more efficient

* Close pc as well
This commit is contained in:
Nicolas Mowen 2023-10-20 17:20:38 -06:00 committed by GitHub
parent facd557f8c
commit b4d5a3ef14
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,10 +1,11 @@
import { h } from 'preact'; import { h } from 'preact';
import { baseUrl } from '../api/baseUrl'; import { baseUrl } from '../api/baseUrl';
import { useCallback, useEffect } from 'preact/hooks'; import { useCallback, useEffect } from 'preact/hooks';
import { useMemo } from 'react';
export default function WebRtcPlayer({ camera, width, height }) { export default function WebRtcPlayer({ camera, width, height }) {
const url = `${baseUrl.replace(/^http/, 'ws')}live/webrtc/api/ws?src=${camera}`; const url = `${baseUrl.replace(/^http/, 'ws')}live/webrtc/api/ws?src=${camera}`;
const ws = useMemo(() => new WebSocket(url), [url])
const PeerConnection = useCallback(async (media) => { const PeerConnection = useCallback(async (media) => {
const pc = new RTCPeerConnection({ const pc = new RTCPeerConnection({
iceServers: [{ urls: 'stun:stun.l.google.com:19302' }], iceServers: [{ urls: 'stun:stun.l.google.com:19302' }],
@ -60,7 +61,6 @@ export default function WebRtcPlayer({ camera, width, height }) {
const connect = useCallback(async () => { const connect = useCallback(async () => {
const pc = await PeerConnection('video+audio'); const pc = await PeerConnection('video+audio');
const ws = new WebSocket(url);
ws.addEventListener('open', () => { ws.addEventListener('open', () => {
pc.addEventListener('icecandidate', (ev) => { pc.addEventListener('icecandidate', (ev) => {
@ -85,11 +85,19 @@ export default function WebRtcPlayer({ camera, width, height }) {
pc.setRemoteDescription({ type: 'answer', sdp: msg.value }); pc.setRemoteDescription({ type: 'answer', sdp: msg.value });
} }
}); });
}, [PeerConnection, url]);
ws.addEventListener('close', () => {
pc.close();
})
}, [PeerConnection, ws]);
useEffect(() => { useEffect(() => {
connect(); connect();
}, [connect]);
return () => {
ws.close();
}
}, [connect, ws]);
return ( return (
<div> <div>