WebRTC PeerJS文本聊天-同时连接到多个Peerrid

WebRTC PeerJS文本聊天-同时连接到多个Peerrid,webrtc,peerjs,Webrtc,Peerjs,嗨,朋友们,我一直在努力连接到多个对等id进行文本聊天,当我单独连接到一个对等id时,它正在工作 但我在同时连接多个peerid时遇到了问题 例如,对于连接到单个对等点,我们将使用 var conn = peer.connect(peerId); conn.on('open', function() { connect(conn); }); 当我想连接到多个对等ID时 例如:var peerIDs=['peerid 1','peerid 2','pee

嗨,朋友们,我一直在努力连接到多个对等id进行文本聊天,当我单独连接到一个对等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);
    });        
}
for(变量i=0;i
以下是完整的代码:

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>');

}
var userId=new Date().getTime();
//从服务器获取ID
var peer=new peer(userId,{host:'localhost',端口:3031,路径:'/',调试:true});
var-conn;
var连接=[];
//从服务器接收id
对等点打开('open',函数(id){
console.log('id为'+id');
});
//万一出错
peer.on('error',函数(e){
警报(e.message);
})
//等待连接
peer.on('connection',connect);
功能连接(c){
conn=c;
连接[c.peer]。在('data',函数(data){
var mess=document.createElement('div');
mess.innerHTML=''+c.peer+':''+数据;
元素(document.querySelector('.messages')).append(mess);
});
连接[c.peer]。在('close',函数()上{
警报(c.peer+‘已离开聊天室’);
});
}
//当用户单击聊天按钮时
$scope.chat=函数(){
警报(“用户单击了连接按钮”);
变量peerIDs=['peerid 1','peerid 2','peerid 3']
对于(变量i=0;i

您能告诉我们如何实现这一点吗?我们将非常感谢您的帮助。

要同时拥有多个连接,您只需同时处理多个连接即可

// 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;
        }
   }
}
//远程对等方ID和数据通道数组
var remotePeerIds=[],//您需要它来链接特定的DOM元素
连接=[];//这是管理多个连接的地方
//创建一个对等点
var peer=new peer({key:'YOUR_key'});//你可以在这里用你自己的皮夹子
//获取您的本地对等id
对等点打开('open',函数(id){
log('我的对等ID为:'+ID);
});
//启动与其他对等方的连接并处理它
getConnect(remotePeerId){
var conn=peer.connect(remotePeerId);
手部连接(conn);
}
//好的,现在您也需要处理接收到的连接
对等点打开('connection',函数(conn){
手部连接(conn);
});
//手柄连接-这是最重要的部分
手部连接(连接){
remotePeerIds.push(conn.peer);//将远程对等添加到列表
连接on('打开',函数(){
log(“与对等方连接:+remotePeerId”);
连接on(数据),功能(数据){
//您可以对来自此连接的数据执行任何操作-这也是主要部分
数据处理程序(连接,数据);
});
conn.on('错误',函数(){
//处理错误
康涅狄格州联络员;
});
连接on('关闭',函数(){
//手柄连接关闭
connectionClose(康涅狄格州);
});
连接。推动(连接);
});
});
}
//现在你有了多重连接。如果要向所有其他对等方发送消息,只需对所有连接使用for循环即可
函数广播消息(消息){

对于(var i=0;i@luongnv89,谢谢您的回复

但当我尝试连接多个peerID时,我遇到了问题

例如:

    // 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]);     
    } 
所以我所做的就是让它发挥作用我不知道这是否是正确的方法

我只是设置了连接之间的延迟

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);
})();
var peerIDS=['cttgmy43jy30udi0','mhzqhpn8rj4f5hfr'];
var arrLength=peerIDS.length;
var计数=0;
(函数processConnection(){

如果(arrLength),我认为使用peerId的fix数组不是一个好主意。您可以在页面上创建一个输入框来输入远程peerId+“调用”按钮。每当你有新的远程对等连接时,只需输入peerID并单击按钮。顺便说一句,我不必像你那样设置延迟时间,仍然可以同时调用connect到许多其他对等连接:D.@luongnv89:Array of peerID是我的项目要求。实际上,任何在线用户都有一个peerID和他们的peerID,通过socket it wi将存储在服务器中。假设我要呼叫一个同时登录移动和web的人,我将有两个peerID来连接,这就是阵列的功能。如果您有任何其他改进方法,请与我分享。非常感谢您的帮助。是的,在这种情况下,您将有两个peerID用于移动和web。但是您也有为了避免您有两个不同的远程对等点,就像您有来自移动和web的视频,只有一个远程对等点。好的,从日志中,我认为您已经有两个到两个对等点的连接。您可以在浏览器控制台中签入:peer.connections以列出您拥有的所有连接。并且确保在您拨打电话时,两个远程对等点对等id应联机。
remotePeerIds
您没有指定的最重要的。如何使用此数组?
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);
})();