user13178684
user13178684

Reputation:

How to reconnect in Pubnub?

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.

Upvotes: 2

Views: 940

Answers (1)

Fraser
Fraser

Reputation: 17039

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

Upvotes: 1

Related Questions