【问题标题】:WebRTC PeerJS Text Chat - Connect to multiple peerID at the same timeWebRTC PeerJS 文本聊天 - 同时连接到多个 peerID
【发布时间】:2015-06-09 16:43:04
【问题描述】:

嗨朋友们,我一直在努力连接到多个对等 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>');

}

您能否提供有关如何实现此目的的见解。非常感谢您的帮助。

【问题讨论】:

    标签: webrtc peerjs


    【解决方案1】:

    要能够同时拥有多个连接,你只需要同时处理多个连接即可。

    // 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;
            }
       }
    }
    

    这是主要部分,您需要为连接处理程序添加更多代码以防出错并关闭。

    就是这样!

    【讨论】:

    • remotePeerIds 最重要的你没有指定。这个数组怎么用?
    【解决方案2】:

    @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]);     
        } 
    

    当我运行上述循环时,我只能连接到我在数组中传递的最后一个 peerid,在这种情况下它是'mhzqhpn8rj4f5hfr'

    我在这里发布控制台的东西

    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
    

    那么做的是让它工作我不知道这是否是正确的方法......

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

    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);
    })();
    

    现在它工作正常..你能告诉我我是走在正确的道路上还是有其他更好的方法来完成这个

    【讨论】:

    • 我认为使用 peerIDS 的修复数组不是一个好主意。您可以在您的页面上创建一个输入框来输入远程peerId +“呼叫”按钮。每当您有新的远程对等方要连接时,只需输入 peerID 并单击按钮。顺便说一句,我不必像你那样设置延迟时间,仍然可以同时调用连接到许多其他对等点:D。
    • @ luongnv89 : PeerIDs 数组是我的项目要求。实际上,在线的用户都有一个 peerID,他们的 peerID 通过套接字将存储在服务器中。假设如果我想打电话给一个人已登录移动设备和网络,我将有两个 peerID 来正确连接,这就是数组。如果您有任何其他方法可以改进这一点,请与我分享。非常感谢您的帮助。
    • 是的,在这种情况下,您将有两个用于移动设备和 Web 的 peerID。但是您还必须设法避免拥有两个不同的远程对等点,例如您既有来自移动设备的视频,也有来自只有一个远程对等点的网络的视频。好的,从日志中我认为您已经与两个对等点建立了两个连接。您可以检查浏览器控制台: peer.connections 以列出您拥有的所有连接。并确保当您拨打电话时,2 个远程对等 id 应该在线。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多