最近、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.(…)
上記のように「open」イベントがリッスンされている場所...
これが明確であることを願っています-どんな助けも大歓迎です:)