ASP.NET Core SignalR (十)【下】:SignalR Javascript 客户端

错误处理以及日志

        在start 方法的后面链接一个catch 方法来处理客户端的错误。output.error将错误输出到浏览器控制台。

*/

/* this is here to show another alternative to start, with a catch

       当连接建立的时候,可以通过传递一个日志记录器及一种类型的事件给日志记录器来建立客户端的日志追踪。消息以特定的日志级别被记录。如下是可用的日志级别:

  • signalR.LogLevel.Error – 错误消息。仅仅记录 Error 消息。
  • signalR.LogLevel.Warning – 有关潜在错误的告警消息。记录 Warning 以及 Error 消息。
  • signalR.LogLevel.Information – 不包含错误的状态消息。记录 Information,Warning,Error消息。
  • signalR.LogLevel.Trace – 追踪消息。记录所有的消息,包含在 中心 和客户端之间传输的数据。

       使用 HubConnectionBuilder 上的 configureLogging 方法来配置日志级别。消息被记录的浏览器控制台。

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .configureLogging(signalR.LogLevel.Information)
    .build();

重连客户端

        自动重连

        使用 HubConnectionBuilder 上的withAutomaticReconnect方法,可以将 SignalR Javascript 客户端配置为自动重连。默认情况下其不会自动重连。

const connection = new signalR.HubConnectionBuilder()
    .withUrl("/chatHub")
    .withAutomaticReconnect()
    .build();c

       如果不带任何参数,withAutomaticReconnect 会配置客户端在每一次重连尝试之前,分别等待0,2,10,30秒,如果四次重连均失败,那么连接便会停止。

       如果配置了自动重连,在开始每一次重连尝试之前,HubConnection 都会变为 HubConnectionState.Reconnecting 状态并触发它的onreconnecting 回调。而如果没有配置HubConnection 为自动重连,此时(连接断开时)HubConnection 的状态会变为Disconnected 并触发它的onclose 回调。这就提供了一个时机来警告用户连接已经丢失,并禁用掉相关的UI元素。

connection.onreconnecting((error) => {
    console.assert(connection.state === signalR.HubConnectionState.Reconnecting);

    document.getElementById("messageInput").disabled = true;

    const li = document.createElement("li");
    li.textContent = `Connection lost due to error "${error}". Reconnecting.`;
    document.getElementById("messagesList").appendChild(li);
});

       如果客户端在它的前四次重连尝试之内成功连接,HubConnection 会重新变回Connected 状态并触发它的onreconnected 回调。这提供了一个时机来通知用户连接已经重新建立。

猜你喜欢

转载自www.cnblogs.com/qianxingmu/p/12550841.html