gpt4 book ai didi

blazor - 如何在生产中部署 Blazor 服务器并克服 SignalR 重新连接问题?

转载 作者:行者123 更新时间:2023-12-04 01:34:38 25 4
gpt4 key购买 nike

Blazor 服务器是一项了不起的技术,但它经常因 SignalR 无法重新连接到服务器而中断。

如何在生产中解决这个问题?我让人们让他们的笔记本电脑处于 sleep 状态或将手机与网站放在 5 秒钟之外,而不是“尝试重新连接”。

而且总是失败。用户正在等待看到“重新加载”按钮。

即使网站在移动浏览器或 sleep 电脑的浏览器中未处于事件状态,如何克服这个问题并强制重新连接 SignalR?

最佳答案

概述
Blazor 内置了用于自定义启动过程的选项,但它们并没有被很好地记录下来。
据我所知,这就是:Configure the SignalR client for Blazor Server apps
但是,还有更多选项,包括设置重新连接选项的能力。
样本
在下面的代码示例中,我设置了 maxRetries 和 retryIntervalMilliseconds(第 48/49 行)——它们定义了客户端在发生通信故障时尝试重新连接的积极程度。
我还配置了一个自定义 reconnectionHandler(第 51 行),其最小实现将尝试重新连接(不显示任何 UI),如果所有尝试都失败,它将简单地重新加载页面。
这不是一件特别聪明的事情,但它可以作为一个示例来演示您可以如何自定义流程。
进一步阅读
AspNetCore Circuits Client Side Code
** 请不要在生产中使用此 sample - 它仅用于说明 **
首先,使用 autostart="false" 关闭 Blazor 启动过程

<script autostart="false" src="_framework/blazor.server.js"></script>
然后,您可以提供自己的连接处理程序和设置
<script>
async function connectionDown(options) {
console.log("Connection Down - you could do some UI here...");
for (let i = 0; i < options.maxRetries; i++) {
console.log("Waiting for reconnect attempt #"+(i+1)+" ...");
await this.delay(options.retryIntervalMilliseconds);
if (this.isDisposed) {
break;
}

try {
// reconnectCallback will asynchronously return:
// - true to mean success
// - false to mean we reached the server, but it rejected the connection (e.g., unknown circuit ID)
// - exception to mean we didn't reach the server (this can be sync or async)
console.log("Starting Reconnect attempt #"+(i+1)+" ...");
const result = await window.Blazor.reconnect();
if (!result) {
// If the server responded and refused to reconnect, log it
console.error("Server Rejected");
} else {
// Reconnected!
return;
}
} catch (err) {
// We got an exception so will try again
console.error(err);
}
}
// all attempts failed - let's try a full reload
// This could be a UI change instead or something more complicated
location.reload();
}

function delay(durationMilliseconds) {
return new Promise(resolve => setTimeout(resolve, durationMilliseconds));
}

function connectionUp(e) {
// Reconnected
console.log("Connection UP!");
// if you have a UI to hide/change you can do that here.
}

window.Blazor.start({
reconnectionOptions: {
maxRetries: 30,
retryIntervalMilliseconds: 500,
},
reconnectionHandler: {
onConnectionDown: e => connectionDown(e),
onConnectionUp: e => connectionUp(e)
}
});
</script>

关于blazor - 如何在生产中部署 Blazor 服务器并克服 SignalR 重新连接问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60031791/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com