嗨朋友们,当我单独连接到单个对等点时,我一直在努力连接到多个对等点 ID 进行文本聊天,它正在工作
但我在同时连接多个peerid时遇到问题
例如,为了连接到单个对等点,我们将使用它
var conn = peer.connect(peerId);
conn.on('open', function() {
connect(conn);
});
当我想连接到多个对等 ID 时
例如:var peerIDs = ['peerid 1', 'peerid 2', 'peerid 3']
我为此使用循环
for(var i=0 ; i < peerIDs.length ; i++){
conn = peer.connect(peerIDs[i]);
conn.on('open', function() {
connect(conn);
});
}
这是完整的代码:
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>');
}
您能否提供有关如何实现这一目标的见解。您的帮助将不胜感激。