满足我的条件后,如何使用AutomaticReconnect处理或销毁它?无论我尝试什么,该方法每次都会执行。
const connection = new signalR.HubConnectionBuilder()
.withUrl(socketServerUrl, {
withCredentials: false,
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
})
.withAutomaticReconnect({
nextRetryDelayInMilliseconds: ({ elapsedMilliseconds }) => {
// function content
},
})
.configureLogging(signalR.LogLevel.Information)
.build();
if (isGameSessionExpired) {
// Looking for something like that, but didn't work
connection.stop();
connection.withAutomaticReconnect(null);
connection = null;
}
需要注意的是,一旦
connection
被声明为 const
,就不能将其重新分配给 null
。
我刚刚优化了代码,一切正常,你可以尝试一下。
let allowReconnect = true; // allow reconnect by default
const connection = new signalR.HubConnectionBuilder()
.withUrl(socketServerUrl, {
withCredentials: false,
skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets,
})
.withAutomaticReconnect({
nextRetryDelayInMilliseconds: ({ elapsedMilliseconds }) => {
if (!allowReconnect) {
return null; // don't reconnect any more
}
// other logic here if you have
},
})
.configureLogging(signalR.LogLevel.Information)
.build();
if (isGameSessionExpired) {
allowReconnect = false; // update the allowReconnect flag to prevent the reconnect behavior
connection.stop(); // stop the connection
}