Javascript connection.disconnected不是一个函数

Javascript connection.disconnected不是一个函数,javascript,asp.net-core,signalr,Javascript,Asp.net Core,Signalr,我很困惑: 我正在使用带Asp.Net内核的信号器和JavaScript客户端。我只想检测断开连接并自动重新连接 在谷歌搜索了很多次之后,我想到了这个: connection.disconnected(function() { setTimeout(function() { $.connection.hub.start(); }, 5000); // Restart connection after 5 seconds. }); 但我得到了一个错误: connecti

我很困惑:

我正在使用带Asp.Net内核的信号器和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 () {
给出了:

我也试过:

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. 

我想你说的不对,试试这个

connection.on("disconnect", function() {
   setTimeout(function() {
       $.connection.hub.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();
});

参考资料:

嗨,谢谢你。它不起作用。断开连接事件未触发。我还将其更改为: