WebRTC PeerJS Text Chat - Connect to multiple peerID at the same time

4.9k views Asked by At

Hi friends I have been working on to connect to multiple peer id for text chat when i connect to single peer alone it is working

but i am getting problem on connecting multiple peerid at the same time

For example for connecting to single peer we will be using this

    var conn = peer.connect(peerId);

    conn.on('open', function() {
        connect(conn);
    });

When i want to connect to multiple peer ID

For ex : var peerIDs = [ 'peerid 1', 'peerid 2', 'peerid 3']

I am using loop for this

for(var i=0 ; i < peerIDs.length ; i++){
    conn = peer.connect(peerIDs[i]);

    conn.on('open', function() {
        connect(conn);
    });        
}

Here is the complete code:

var userId = new Date().getTime();
//Get the ID from the server
var peer   = new Peer(userId, {host: 'localhost', port: 3031, path: '/',debug: true }); 

var conn;
var connections = [];

//to receive id from the server
peer.on('open', function(id){
    console.log('the id is'  +id);

});

//in case of error
peer.on('error', function(e){
    alert(e.message);
})

//Awaits for the connection
peer.on('connection', connect);

function connect(c){

    conn = c;

    connections[c.peer].on('data', function(data){

        var mess = document.createElement('div');
        mess.innerHTML = '<span class="peer">' + c.peer + '</span>: ' + data;
        angular.element( document.querySelector( '.messages' ) ).append(mess);


    });

    connections[c.peer].on('close', function(){

        alert(c.peer + 'has left the chat');

    });



}

//When user clicks the chat button
$scope.chat = function(){
    alert('user clicked the connect button');

    var peerIDs = [ 'peerid 1',  'peerid 2', 'peerid 3'] 
    for(var i=0 ; i < peerIDs.length ; i++){
        var conn = peer.connect(peerIDs[i]);

        conn.on('open', function() {
            connections.push(c);
            connect(conn);
        });        
    }


}

//send message  when clicked
$scope.send = function(){

    // For each active connection, send the message.
    var msg = angular.element( document.querySelector( '#mess' ) ).val();

    //Send message to all connected peers
    for(var i in connections){
        connections[i].send(msg);
    }

    angular.element( document.querySelector( '.messages' ) ).append('<div><span class="you">You: </span>' + msg
          + '</div>');

}

Can you please give the insight of how to achieve this.Your help will be Greatly appreciated.

2

There are 2 answers

1
luongnv89 On

To be able to have multi-connections at the same time, you just need to handle multi-connections at the same time.

// Array of remote peers ID and data channel
var remotePeerIds=[],// You need this to link with specific DOM element
connections=[]; // This is where you manage multi-connections

// create a Peer
var peer = new Peer({key: 'YOUR_KEY'}); // You can use your own peerID here

// Get your local peer id
peer.on('open', function(id) {
  console.log('My peer ID is: ' + id);
});

// Start connection with other peer - and handle it
getConnect(remotePeerId){
    var conn = peer.connect(remotePeerId);
    handleConnection(conn);
}

// Ok now you need to handle the received connection too
peer.on('connection',function(conn){
     handleConnection(conn);
});

// Handle connection - this is most important part
handleConnection(conn){
    remotePeerIds.push(conn.peer); // Add remote peer to list

    conn.on('open', function() {
        console.log("Connected with peer: "+remotePeerId);
        conn.on('data',function(data){
           // You can do whatever you want with the data from this connection - this is also the main part
           dataHandler(conn,data);
        });
        conn.on('error',function(){
          // handle error 
          connectionError(conn);
        });

        conn.on('close',function(){
          // Handle connection closed
          connectionClose(conn);
        });
        connections.push(conn);
    });
  });
}

// So now you have multi-connections. If you want to send a message to all other peer, just using for loop with all the connections
function broadcastMessage(message){
    for(var i=0;i<connections.length,i++){
        connections[i].send(message);
    }
}

// Or if you want to send a message to a specific peer - you need to know his peerid

function privateMessage(remotePeerId,message){
   for(var i=0;i<connections.length,i++){
        if(connections[i].peer==remotePeerId){
           connections[i].send(message);
           break;
        }
   }
}

This is the main part, you need to add some more code for connection handler in case of error and close.

That's it !

3
sdg On

@luongnv89 Thanks for your response.

But i am getting problem when i try to connect multiple peerID

For Ex :

    // Start connection with other peer - and handle it
    function getConnect(remotePeerId){
        var conn = peer.connect(remotePeerId);
        handleConnection(conn);
    } 

    var peerIDS = ['cttgmy43jy30udi0', 'mhzqhpn8rj4f5hfr'];

    for(var i=0 ; i < peerIDS.length ; i++){
        getConnect(peerIDS[i]);     
    } 

When i ran the above loop i can able to connect with only the last peerid which i pass in the array in this case it is 'mhzqhpn8rj4f5hfr'

Here i post the console thing

PeerJS:  Creating RTCPeerConnection.
peer.min.js:1 PeerJS:  Listening for ICE candidates.
peer.min.js:1 PeerJS:  Listening for `negotiationneeded`
peer.min.js:1 PeerJS:  Listening for data channel
peer.min.js:1 PeerJS:  Listening for remote stream
peer.min.js:1 PeerJS:  Creating RTCPeerConnection.
peer.min.js:1 PeerJS:  Listening for ICE candidates.
peer.min.js:1 PeerJS:  Listening for `negotiationneeded`
peer.min.js:1 PeerJS:  Listening for data channel
peer.min.js:1 PeerJS:  Listening for remote stream
2peer.min.js:1 PeerJS:  `negotiationneeded` triggered
peer.min.js:1 PeerJS:  Created offer.
peer.min.js:1 PeerJS:  Set localDescription: offer for: cttgmy43jy30udi0
peer.min.js:1 PeerJS:  Created offer.
peer.min.js:1 PeerJS:  Received ICE candidates for: cttgmy43jy30udi0
peer.min.js:1 PeerJS:  Set localDescription: offer for: mhzqhpn8rj4f5hfr
peer.min.js:1 PeerJS:  Received ICE candidates for: mhzqhpn8rj4f5hfr
peer.min.js:1 PeerJS:  Setting remote description RTCSessionDescription {sdp: "v=0
↵o=- 8190108536299128797 2 IN IP4 127.0.0.1
↵s…id:data
↵a=sctpmap:5000 webrtc-datachannel 1024
↵", type: "answer"}
peer.min.js:1 PeerJS:  Added ICE candidate for: cttgmy43jy30udi0
peer.min.js:1 PeerJS:  Set remoteDescription: ANSWER for: cttgmy43jy30udi0
2peer.min.js:1 PeerJS:  Added ICE candidate for: cttgmy43jy30udi0
2peer.min.js:1 PeerJS:  Received ICE candidates for: mhzqhpn8rj4f5hfr
peer.min.js:1 PeerJS:  Data channel connection success
peer.min.js:1 PeerJS:  Setting remote description RTCSessionDescription {sdp: "v=0
↵o=Mozilla-SIPUA-35.0.1 15417 0 IN IP4 0.0.0.0…ap:5000 webrtc-datachannel 1024
↵a=setup:active
↵", type: "answer"}
2peer.min.js:1 PeerJS:  Added ICE candidate for: mhzqhpn8rj4f5hfr
peer.min.js:1 PeerJS:  Set remoteDescription: ANSWER for: mhzqhpn8rj4f5hfr
peer.min.js:1 PeerJS:  Added ICE candidate for: mhzqhpn8rj4f5hfr
peer.min.js:1 PeerJS:  Data channel connection success
peer.min.js:1 PeerJS:  Added ICE candidate for: mhzqhpn8rj4f5hfr

So what did is to make it work i dont know whether it is the right approach or not...

I just set the delay between connections

var peerIDS   = ['cttgmy43jy30udi0', 'mhzqhpn8rj4f5hfr'];
var arrLength = peerIDS.length;
var count     = 0;

(function processConnection(){

    if(arrLength <= count) return;

    getConnect(peerIDS[count]);
    count++;
    setTimeout(function(){
        processConnection()
    }, 5000);
})();

And now it is working properly..Can you please tell me whether i am going in a right path or is there anyother better way to accomplish this