PeerJS自动重新连接

PeerJS Auto Reconnect

本文关键字:重新连接 PeerJS      更新时间:2023-09-26

我最近使用PeerJS开发了一个web应用程序,并尝试添加重新连接功能。

基本上,我的应用程序是由某人创建服务器来工作的,客户端然后连接到该服务器。服务器人员可以控制主机的操作,但基本的双向通信除外。

如果客户端断开连接,他们只需重新连接即可正常工作。但是,如果服务器用户刷新页面,或者他们的计算机崩溃,那么他们需要能够重新建立对客户端的控制。

首先是重新获得原始连接ID和对等api ID,这很好,也很容易,因为它们存储在数据库中,并分配了一个唯一的ID,服务器用户可以使用它来查询它们。然后,为了使客户端能够重新连接,我在关闭时这样做:

// connection is closed by the host involuntarily...
conn.on('close', function() { 
    // if the clients connection closes set up a reconnect request loop - when the host takes back control
    // the client will auto reconnect...
    connected = false;
    conn = null;
    var reconnect_timer = setInterval(function () {
        console.log('reconnecting...'); // make a fancy animation here...
        conn = peer.connect(connectionid, {metadata: JSON.stringify({'type':'hello','username':username})});    
        // upon connection
        conn.on('open', function() { // if this fails need to provide an error message... DO THIS SOON      
            // run the connect function...
            connected = true;
            connect(conn);      
        });
        // didnt connect yet
        conn.on('error', function(err) {
            connected = false;
        });
        if(connected === true) {
            clearInterval(reconnect_timer);
        }
    }, 1000);
});

这似乎是有效的,因为在服务器端,客户端看起来已经重新连接-连接功能已经启动等。然而,消息无法在两者之间发送,客户端控制台显示:

Error: Connection is not open. You should listen for the `open` event before sending messages.(…)

如果"公开"事件显示为已在上面收听。。。

我希望这是清楚的-感谢任何帮助:)

因此,最终要创建一个自动重新连接脚本,我只需处理客户端的事务,确保服务器设置为相同的api_key(对于cloudserver)和key:

peer = new Peer(return_array.host_id, {key: return_array.api_key});

然后拥有客户端,在连接关闭时:

// connection is closed by the host involuntarily...
conn.on('close', function() { 
    // if the clients connection closes set up a reconnect request loop - when the host takes back control
    // the client will auto reconnect...
    peer.destroy();     // destroy the link
    connected = false;  // set the connected flag to false
    conn = null;        // destroy the conn
    peer = null;        // destroy the peer
    // set a variable which means function calls to launchPeer will not overlap
    var run_next = true;
    // periodically attempt to reconnect
    reconnect_timer = setInterval(function() { 
        if(connected===false && run_next===true) {
            run_next = false;   // stop this bit rerunning before launchPeer has finished...
            if(launchPeer(false)===true) { 
                clearInterval(reconnect_timer); 
            } else run_next == true;
        }       
    }, 1000);
});

启动对等方将尝试启动新对等方。为了确保连续性,来自客户端的新id将取代来自客户端的旧id,一切都是顺利接管。最后最困难的部分是"setInterval"只触发一次,这是通过使用布尔标志实现的(糟糕的…)。

感谢任何阅读并思考如何提供帮助的人:)