#reactjs #socket.io #webrtc
#реагирует на #socket.io #webrtc
Вопрос:
Я использую react, сокет.io и WebRTC.Первое соединение отличное, но в следующий раз возникает проблема, я думаю, что эта проблема на SDP не обновляется. Я уже вызываю close() одноранговое соединение.
Код ошибки:
Ошибка InvalidAccessError: Не удалось выполнить «addTrack» в «RTCPeerConnection»: Отправитель для трека уже существует.
Моя функция initCall была вызвана в useEffect.
let configRTC = { iceServers: [{ urls: 'stun:stun.l.google.com:19302' }] }; let localConnection = new RTCPeerConnection(configRTC); let remoteConnection = new RTCPeerConnection(configRTC); const initCall(stream,loca)=gt;{ socket.on('other-users', (socketId) =gt; { console.log('other user'); conn = localConnection; stream.getTracks().forEach((track) =gt; localConnection.addTrack(track, stream)); localConnection.onicecandidate = ({ candidate }) =gt; { candidate amp;amp; socket.emit('candidate', { socketId, candidate }); }; // Receive stream from remote client and add to remote video area localConnection.ontrack = ({ streams: [stream] }) =gt; { if (!remoteVideo.current) return; remoteVideo.current.srcObject = stream; }; localConnection .createOffer({ offerToReceiveAudio: 1, offerToReceiveVideo: 1, iceRestart: true }) .then((offer) =gt; localConnection.setLocalDescription(offer)) .then(() =gt; { socket.emit('offer', { socketId, description: localConnection.localDescription}); }); socket.on('offer', (data) =gt; { // Ininit peer connection console.log('offer', data.socketId); console.log('des', data.description); // remoteConnection = new RTCPeerConnection(configRTC); conn = remoteConnection; console.log('remote', remoteConnection.signalingState); console.log('remoteTRICKLE', remoteConnection.iceGatheringState); remoteConnection.onnegotiationneeded = (event) =gt; { try { console.log(remoteConnection.signalingState); console.log(this.remoteConnection.signalingState); } catch (e) { console.log(e); } }; conn = remoteConnection; remoteConnection.restartIce(); stream.getTracks().forEach((track) =gt; remoteConnection.addTrack(track, stream)); remoteConnection.onicecandidate = ({ candidate }) =gt; { candidate amp;amp; socket.emit('candidate', { socketId: data.socketId, candidate }); }; // Receive stream from remote client and add to remote video area remoteConnection.ontrack = ({ streams: [stream] }) =gt; { remoteVideo.current.srcObject = stream; }; remoteConnection .setRemoteDescription(data.description) .then(async () =gt; await remoteConnection.createAnswer()) .then(async (answer) =gt; await remoteConnection.setLocalDescription(answer)) .then(() =gt; { console.log('answer', data.socketId); console.log('answerDes', remoteConnection.localDescription); socket.emit('answer', { socketId: data.socketId, description: remoteConnection.localDescription }); }); } }); socket.on('answer', (data) =gt; { let description = new RTCSessionDescription(data.description); localConnection.setRemoteDescription(description); }); socket.on('candidate', (candidate) =gt; { let can = new RTCIceCandidate(candidate); conn.addIceCandidate(can); }); return; };
Комментарии:
1. Эта проблема возникла из-за того, что я забыл закрыть( отписаться) сокет
socket.off('candidate') socket.off('offer') ...
при отключении компонента. Спасибо всем.
Ответ №1:
Вы просто повторяете попытку добавить тот же MediaStreamTrack к тому же Peerconnection, у которого он уже есть. ex :
var medias = null; var rc = null; var p = new RTCPeerConnection(); navigator.mediaDevices.getUserMedia({audio: true}).then((res)=gt; { medias = res; p.addTrack(medias.getTracks()[0]) p.addTrack(medias.getTracks()[0]) // throw Uncaught DOMException: Failed to execute 'addTrack' on 'RTCPeerConnection': A sender already exists for the track. });