asad nextstair
asad nextstair

Reputation: 35

How to setup multiple peer connection with datachannels?

The code below is working fine for a simple 1 to 1 peer connection but I want to do it for multiple peers so that each peer is connected to others by forming a mesh network.

I am using node js web socket for the signaling server.

Can anyone help how can I do that?

var rtcPeerConnection;
let dataChannel;
const dataChannelOptions = { ordered: true, negotiated: true, id: 0 };
const socket = new WebSocket('ws://signaling-server.ap-1.evennode.com');
        // const socket = new WebSocket('ws://127.0.0.1:3000');
        var configuration = {
                "iceServers": [
            
                { 
                    url: 'turn:freeturn.net:3478',
                    credential: 'free',
                    username: 'free'
                 },
                 { 
                    url: 'turn:relay1.expressturn.com:3478',
                    credential: '7a2Pma38DEdRAq9e',
                    username: 'ef4WN6DX2SWZ2CJ2VL'
                 },
                {
                  
                    urls: [
                        "stun:stun.l.google.com:19302",
                        "stun:stun.services.mozilla.com"
                     ]
                }

               ]
           }

           rtcPeerConnection = new RTCPeerConnection(configuration);
        cntBtn.onclick = () => {
            
            dataChannel = rtcPeerConnection.createDataChannel('textChat', dataChannelOptions);
            rtcPeerConnection.onicecandidate = (e) => {
                console.log('ICE', e);
                socket.send(JSON.stringify({
                    type: 'candidate',
                    data: e.candidate
                }));
            }
            dataChannel.onmessage = event => receiveMessage(event.data);
            rtcPeerConnection.createOffer()
                .then(offer => rtcPeerConnection.setLocalDescription(offer))
                .then(() => {
                    socket.send(JSON.stringify({
                        type: 'offer',
                        data: rtcPeerConnection.localDescription
                    }));
                })
                .then(() => { console.log('Offer Sent') })
                .catch(error => console.error('Error creating offer:', error));
        }


        function sendMessage() {
            const message = messageInput.value;
            if (message.trim() !== '') {
                chatBox.value += `You: ${message}\n`;
                sendData(message);
                messageInput.value = '';
            }
        }
        function receiveMessage(message) {
            chatBox.value += `Peer: ${message}\n`;
        }
        function sendData(data) {
            console.log(dataChannel.readyState)
            if (dataChannel && dataChannel.readyState === 'open') {
                dataChannel.send(data);
            }
        }

        socket.onopen = e => {
            console.log('Connected To the Signaling Server')
        }
        socket.onmessage = async event => {
            const message = JSON.parse(event.data.toString());
            if (message.type === 'answer') {
                console.log('Answer Recived: ', message.data)
                await rtcPeerConnection.setRemoteDescription(message.data);
            } else if (message.type === 'offer') {
                console.log('Offer Recived: ', message.data)
                await rtcPeerConnection.setRemoteDescription(message.data);
                const answer = await rtcPeerConnection.createAnswer();
                await rtcPeerConnection.setLocalDescription(answer);
                socket.send(JSON.stringify({
                    type: 'answer',
                    data: rtcPeerConnection.localDescription
                }));
            } else if (message.type === 'candidate') {
                console.log('Adding ICE Candidate')
                rtcPeerConnection.addIceCandidate(message.data);
            }
        };

Where I can implement the logic for multiple peers connection.

Upvotes: 0

Views: 46

Answers (0)

Related Questions