PeerJS自动重新连接
PeerJS Auto Reconnect
我最近使用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"只触发一次,这是通过使用布尔标志实现的(糟糕的…)。
感谢任何阅读并思考如何提供帮助的人:)
相关文章:
- 当客户端在JW Player中恢复丢失的连接时,会自动重新连接
- PeerJS自动重新连接
- Node.js REST与MySQL句柄重新连接
- Socket.IO socket.id 更改同一客户端而不重新连接
- 设置流星重新连接时间
- 如何通过重新连接实现共享重播
- 重新连接具有共享RxJS observable的WebSocket
- 重新连接 JavaScript 函数
- 如何在自动重新连接超时后重新连接socket.io客户端
- Socket.IO:重新连接导致服务器连接代码运行两次
- node.js/socket.io:重新连接时刷新表
- 套接字发出 重新连接套接字后不触发
- Socket.io :断开连接后重新连接时如何执行某些操作
- 断开并手动重新连接 Socket.IO
- Socket.io 数据包在断开连接和重新连接之间丢失
- 重新连接并断开突变观察者
- Ajax 查询,无需重新连接到数据库
- 套接字 IO 重新连接
- 为什么客户端在节点+快递+socket.io+翡翠简单应用中断开连接再重新连接
- 睡眠后重新连接插座