问题
I am using PubNub for notifications transfer across my Js code. I am unable to figure out how to reconnect in PubNub once internet disconnects and comes back up.
having restore: true in my init and doing
this.listeners = {
message: msgEvent => {
console.log(msgEvent);
},
status: statusEvent => {
if (statusEvent.category === "PNNetworkUpCategory") {
this.pubnub.reconnect();
}}};
Doesn't work for me.
full code:
this.pubnub = new PubNub({
subscribeKey: this.serverDetails.authInfo.subscribeKey,
authKey: this.serverDetails.authInfo.authKey,
uuid,
restore: true
ssl: true
});
this.listeners = {
message: msgEvent => {
console.log(msgEvent);
},
status: statusEvent => {
if (statusEvent.category === "PNNetworkUpCategory") {
this.pubnub.reconnect();
}
}
};
this.pubnub.addListener(this.listeners);
SDK: 4.27.2
expectation: try to Reconnect PubNub max N tries) ,subscribe to existing subscribed channels.
回答1:
this.pubnub = new PubNub({
subscribeKey: this.serverDetails.authInfo.subscribeKey,
authKey: this.serverDetails.authInfo.authKey,
uuid,
restore:true,
ssl: true,
});
this.listeners = {
message: (msgEvent) => {
console.dir(msgEvent);
}
status: statusEvent => {
if (statusEvent.category === "PNNetworkUpCategory") {
this.pubnub.subscribe();
}
};
this.pubnub.addListener(this.listeners);
Should work.
回答2:
Looking at it you are possibly getting some other status response that you are not checking for...Also I think you would require the autoNetworkDetection
flag to announce when the network is down or up using the states PNNetworkDownCategory
and PNNetworkUpCategory
. i.e.
this.pubnub = new PubNub({
subscribeKey: this.serverDetails.authInfo.subscribeKey,
authKey: this.serverDetails.authInfo.authKey,
uuid,
restore: true,
ssl: true,
autoNetworkDetection: true
});
this.listeners = {
message: msgEvent => {
console.log(msgEvent);
},
status: statusEvent => {
if (statusEvent.category === "PNNetworkUpCategory") {
this.pubnub.reconnect();
} else {
// check for other status events - PNTimeoutCategory, PNNetworkIssuesCategory, etc
console.log(statusEvent.category);
}
}
};
If that fails and you still get reconnection issues you should set the flag listenToBrowserNetworkEvent
to false
as this allows the SDK reconnection logic to take over. i.e.
this.pubnub = new PubNub({
subscribeKey: this.serverDetails.authInfo.subscribeKey,
authKey: this.serverDetails.authInfo.authKey,
uuid,
restore: true,
ssl: true,
listenToBrowserNetworkEvents: false
});
see: https://www.pubnub.com/docs/web-javascript/pubnub-network-lifecycle#pnnetworkupcategory
来源:https://stackoverflow.com/questions/61064086/how-to-reconnect-in-pubnub