检测SignalR Core连接是否丢失

7

我正在尝试检测SignalR Core连接何时丢失,以便我可以创建一个新的连接或者至少警告用户。

connection.on('closed', data => {
    alert('Connection Closed');
});

这似乎没有任何效果。消息停止到达,但是此处理程序未被触发。

另外,关于事件处理的文档在这个库的新版本中在哪里可以找到?


1
可能是如何从SignalR客户端确定服务器断开连接?的重复问题。 - Sunny Patel
一个快速的谷歌搜索让我找到了这个MS Doc - 处理连接生命周期事件 - Sunny Patel
但是新的Core版本具有不同的API。 - Ian Warburton
2个回答

13

使用 onclose

connection.onclose(function (e) {
    alert('Connection Closed');
}

目前还没有文档,但在 GitHub 上有一些示例


2
它什么时候触发?如果我关闭我的Web服务器,页面似乎毫不知情。 - Ian Warburton
Ian Warburton,看起来需要一些时间,但确实会发生。我也在努力弄清楚这个问题。 - Don Rolling

0
非常感谢aaron!!
虽然这是一篇老文章,但或许会对新手学习SignalR有所帮助。
我找到了文档和一些重新连接的示例。
const connection = new signalR.HubConnectionBuilder()
.withUrl("/chathub")
.configureLogging(signalR.LogLevel.Information)
.build();

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

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

// Start the connection.
start();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接