使用 peer.js,您必须知道要连接的对等方的连接 ID。这意味着您需要一些服务器端逻辑来代理连接。
如果你总是想连接最新的两个传入客户端,你可以简单地从 1 作为 id 开始,尝试构建 Peer,当它失败时,增加 id 并重试。然后,如果你用奇数成功了,什么也不做,当你用偶数成功时,打开一个到 yourid - 1 的连接并开始使用这个连接:
// Use id prefix so we don't collide with other users on peer cloud server
let id_prefix = 'quarnos-';
let id = 0;
let peer = null;
let connection = null;
// Try to initialize peer using incrementing id
do {
id++;
peer = new Peer(id_prefix + id);
} while (!peer);
// When someone connects to us, save connection and log message
peer.on('connection', function(incoming_connection) {
incoming_connection.on('data', function(data){
if (!connection) {
connection = incoming_connection;
connection.send('connection established');
}
console.log(data);
// Here you could put some timed connection.send() logic to make it go back and forth between peers, as requested in the OP
});
});
// A peer with an even id tries to connect to the peer with id one lower (peer 2 connects to peer 1, etc.)
if (id % 2) {
let connection = peer.connect(id_prefix + (id - 1));
connection.on('open', function(){
console.log('trying to establish connection to ' + id_prefix + (id - 1));
connection.send('connection opened by ' + (id_prefix + id));
});
}
这应该在对等 2 和对等 1 上打印trying to establish connection to quarnos-1
and 您应该真正实现一些管理连接的服务器端逻辑,并可能将连接 ID 存储在 cookie 中,以便您可以在页面重新加载时重新连接到同一个对等点。connection established
connection opened by quarnos-2