我最近开发了一个使用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.(…)当“开放”事件被显示为在上面被聆听时.
我希望这是明确的--任何帮助都会受到感谢:)
发布于 2016-05-06 01:16:53
最后,为了创建一个自动重新连接脚本,我只需要处理客户端,确保服务器设置为相同的api_key (用于cloudservers)和键:
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“才能实现(糟糕的.)通过使用布尔标志。
感谢所有阅读并思考如何帮助他们的人:)
https://stackoverflow.com/questions/37041803
复制相似问题