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.
To be able to have multi-connections at the same time, you just need to handle multi-connections at the same time.
This is the main part, you need to add some more code for connection handler in case of error and close.
That's it !