How to reconnect WebSocket automatically before calling loadSubtreeFromModel

Hi Team,

I’m handling a situation where my viewer’s websocketConnectionClosed callback gets triggered (for example, after a couple of minutes of inactivity).

websocketConnectionClosed: async () => {
  console.log("callbacks.websocketConnectionClosed");
},

After this event, if I later call:

await this._viewer.model.loadSubtreeFromModel(rootNodeId, fileName);

it fails, since the WebSocket connection to the Communicator server has already been closed.

I’d like to check whether the connection is still active before calling loadSubtreeFromModel, and if it’s closed, automatically restart or reconnect the viewer session.

I tried checking this._viewer.webSocket or similar properties, but the IWebViewer interface doesn’t expose any connection status or readyState.

Is there any recommended or supported way to:

  1. Detect if the viewer is still connected to the server before making server-dependent calls, and

  2. Reconnect (or reinitialize) the viewer session automatically if the WebSocket is closed?

For reference, I’m using the IWebViewer class, and the main call looks like this:

await this._viewer.model.loadSubtreeFromModel(rootNodeId, fileName);

Any example or best-practice guidance on how to handle reconnection would be greatly appreciated.

Thanks in advance!
— Raja

Perhaps the cleanest way to handle your situation is to create a global bool variable storing the status of the connection, for example:

let isWebSocketConnectionClosed = false;

websocketConnectionClosed: async () => {
	isWebSocketConnectionClosed = true;
  console.log("callbacks.websocketConnectionClosed");
},

It would then just be matter of checking the status of isWebSocketConnectionClosed prior to loading another model.

Once a viewer session has closed, you cannot just reconnect. In essence, you would have to start a whole new session.

As an aside, it’s possible to control the timeout duration via the function setClientTimeout.

  this.\_viewer.setClientTimeout(60, 60); i have set this but with in 2 mins my connection timedout why ?

There is a separate callback for timeout. You can try setting a timeout callback to confirm that the Websocket connection is being lost due an actual timeout event or something else. Perhaps there is another setting in your configuration that closes the Websocket after 2 minutes.

what is that? there is another setting in your configuration that closes the Websocket after 2 minutes.

The connection may be being proactively closed due to your firewall setting or your cloud solution configuration. You will have to check this in your environment.