webrtcsimple-peer

"what is the proper way to disconnect peers using simple-peer.js library and stop streaming between those peers? "


i hope y'all will be fine,

I am a beginner in webRTC sorry if my question feels like a noob one but i was wondering that is there any proper way to close the connection among peers especially using simple-peer.js, looking forward for your awesome replies

here is my sample react code,

 if (navigator.getUserMedia) {
            navigator.getUserMedia({ audio: { echoCancellation: true }, video: true }, stream => {

                let peer = new Peer({
                    initiator: this.props.isInitiator,
                    stream
                });

                this.localStream.current.srcObject = stream;
                this.localStream.current.play();

                peer.on('signal', (data) => {
                    socket.emit('offer', { data: JSON.stringify(data), conversation_id: this.props.conversation_id })
                });

                socket.on('offer', (data) => {
                    peer.signal(JSON.parse(data))
                })

                socket.on('DESTROY-VIDEO-CALL-SESSION', () => {
                    stream.getTracks().forEach(track => track.stop());
                    peer.removeAllListeners();
                    peer.destroy();
                });

                peer.on('stream', (streamData) => {
                    this.remoteStream.current.srcObject = streamData;
                    this.remoteStream.current.play();
                });

                this.setState({
                    endCall: () => {
                        socket.emit('VIDEO-CALL-ENDED', this.props.conversation_id);
                    }
                })

            }, error => {
                alert('Please allow video and audio permission to make this call')
            });
}

Solution

  • The function is peer.destroy().

    Fyi, if you need to find undocumented API functions in Javascript libraries, you can do this by running your JS file in the browser and pressing F12 to bring up the debugging console. Set a breakpoint after the object that you want to investigate is instantiated:

    Debugging console showing all of a hovered object's properties

    I set a breakpoint AFTER I instantiated peer1 (line 51). Then I hovered over peer1 (line 50) to pop up a menu of all of the properties (methods and fields) belonging to this object. If you're looking for a particular function as in this case, sometimes you find it immediately in this menu, but often you have to expand the property called __proto__ :

    Expanded prototype object showing hidden destroy function property

    You can see the destroy function located here. It's just a guess whether or not a function found in this manner actually does what you want it to do, but luckily in this case it does what we want.