gpt4 book ai didi

javascript - connection.disconnected 不是一个函数

转载 作者:行者123 更新时间:2023-12-02 23:04:50 25 4
gpt4 key购买 nike

我很困惑:)

我将 SignalR 与 Asp.Net Core 和 JavaScript 客户端结合使用。我只想检测断开连接并自动重新连接。

经过多次谷歌搜索后,我想出了这个:

connection.disconnected(function() {
setTimeout(function() {
$.connection.hub.start();
}, 5000); // Restart connection after 5 seconds.
});

但我收到错误:

connection.disconnected is not a function

这是我的整个 JavaScript 客户端:

 $(document).ready(function () {

var divTimeStamp = document.getElementById("divTimeStamp");
var img = document.getElementById('imgTest');
var connection = new signalR.HubConnectionBuilder().withUrl("/NotificationUserHub").build();

//Disable send button until connection is established
document.getElementById("sendButton").disabled = true;

connection.on("ReceiveMessage", function (user, image,timestamp ) {
try {
img.src = 'data:image/png;base64,' + image;
divTimeStamp.innerText = timestamp;
} catch (error) {
console.error(error.toString());
}
});

connection.disconnected(function() {
setTimeout(function() {
connection.start();
}, 5000); // Restart connection after 5 seconds.
});

document.getElementById("sendButton").addEventListener("click", function (event) {
var user = document.getElementById("userInput").value;
var message = document.getElementById("messageInput").value;
connection.invoke("MessageFromClient", user, message).catch(function (err) {
return console.error(err.toString());
});
event.preventDefault();
});
});

更改为:

function connection.disconnected(function () {

给出了这个:

enter image description here

我也尝试过这个:

connection.on("disconnect", function() { 
setTimeout(function() {
connection.start();
}, 5000); // Restart connection after 5 seconds. });

connection.on("disconnected", function() {
setTimeout(function() {
connection.start();
}, 5000); // Restart connection after 5 seconds.

最佳答案

使用微软推荐的方法怎么样

async function start() {
try {
await connection.start();
console.log("connected");
} catch (err) {
console.log(err);
setTimeout(() => start(), 5000);
}
};

connection.onclose(async () => {
await start();
});

引用:https://learn.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.2

关于javascript - connection.disconnected 不是一个函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57637005/

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