Skip to content

Commit

Permalink
try a new reconnect strategy
Browse files Browse the repository at this point in the history
  • Loading branch information
NielsPilgaard committed Mar 30, 2024
1 parent 645d610 commit b93c978
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 1 deletion.
7 changes: 6 additions & 1 deletion src/web/Jordnaer/Components/App.razor
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,12 @@
<body>
@*TODO: Add loading image*@
<Routes @rendermode="RenderModeForPage" />
<script src="_framework/blazor.web.js"></script>

@*Start and reconnection logic based on: https://learn.microsoft.com/en-us/aspnet/core/blazor/fundamentals/signalr?view=aspnetcore-7.0#automatically-refresh-the-page-when-server-side-reconnection-fails*@
<div id="reconnect-modal" style="display: none;"></div>
<script src="_framework/blazor.web.js" autostart="false"></script>
<script src="js/boot.js"></script>

<script src="js/scroll.js?v=1.0"></script>
<script src="js/utilities.js?v=1.0"></script>
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
Expand Down
59 changes: 59 additions & 0 deletions src/web/Jordnaer/wwwroot/js/boot.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
(() => {
const maximumRetryCount = 3;
const retryIntervalMilliseconds = 5000;
const reconnectModal = document.getElementById('reconnect-modal');

const startReconnectionProcess = () => {
reconnectModal.style.display = 'block';

let isCanceled = false;

(async () => {
for (let i = 0; i < maximumRetryCount; i++) {
reconnectModal.innerText = `Attempting to reconnect: ${i + 1} of ${maximumRetryCount}`;

await new Promise(resolve => setTimeout(resolve, retryIntervalMilliseconds));

if (isCanceled) {
return;
}

try {
const result = await Blazor.reconnect();
if (!result) {
// The server was reached, but the connection was rejected; reload the page.
location.reload();
return;
}

// Successfully reconnected to the server.
return;
} catch {
// Didn't reach the server; try again.
}
}

// Retried too many times; reload the page.
location.reload();
})();

return {
cancel: () => {
isCanceled = true;
reconnectModal.style.display = 'none';
}
};
};

let currentReconnectionProcess = null;

Blazor.start({
reconnectionHandler: {
onConnectionDown: () => currentReconnectionProcess ??= startReconnectionProcess(),
onConnectionUp: () => {
currentReconnectionProcess?.cancel();
currentReconnectionProcess = null;
}
}
});
})();

0 comments on commit b93c978

Please sign in to comment.