javascript - connection.disconnected 不是函数
问题描述
我很困惑 :)
我将 SignalR 与带有 JavaScript 客户端的 Asp.Net Core 一起使用。我只想检测断开连接并自动重新连接。
经过大量谷歌搜索后,我想出了这个:
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.
解决方案
使用微软推荐的方法怎么样
async function start() {
try {
await connection.start();
console.log("connected");
} catch (err) {
console.log(err);
setTimeout(() => start(), 5000);
}
};
connection.onclose(async () => {
await start();
});
参考:https ://docs.microsoft.com/en-us/aspnet/core/signalr/javascript-client?view=aspnetcore-2.2
推荐阅读
- flask - 如何自动链接所有 Flask 按钮和具有相同 IP 地址的链接
- mongodb - Parse-Server 源 _rperm 和 _wperm mongo 查询,我应该索引它们吗?
- javascript - 无法使用自定义 ErrorHandler Angular 5 显示后端错误的材料小吃栏
- vue.js - 向/从根元素传递事件和道具
- amazon-web-services - 如何在不使用 IAM 的情况下允许将第 3 方文件上传到私有 S3 存储桶?
- sql - 使用 Redshift 运行 SQL IN 和 NOT IN 时出现奇怪的结果
- sql - 错误数据和除以 0
- c# - C# - 在同一工作组(非域)中的远程计算机上创建用户
- ios - 在 ARKit 中检测平面
- javascript - 如何在java脚本中更改表格行颜色onclick函数