【问题标题】:signalr js client onReconnecting() not fired未触发信号器 js 客户端 onReconnecting()
【发布时间】:2018-03-08 14:44:36
【问题描述】:

我在处理我的 signalR js 客户端上的连接生命周期事件时遇到了问题。我在客户端使用 aspnet/signalr-client npm 库,在 asp.net 核心服务器上使用 microsoft.aspnetcore.signalr 库。

问题是

当我关闭服务器 (alt+F4) 时,客户端方法 onClosed(error) 被触发,我想要的是,documentation 中如何描述它,onReconnecting() 方法被触发并且客户端尝试重新连接。我已经尝试忽略此问题并在onClosed(error) 方法中建立新连接,但随后出现Uncaught (in promise) Error: Cannot start a connection that is not in the 'Initial' state. 错误。

我的问题是

为什么onClosed(error) 方法被触发并且客户端不尝试重新连接,我该如何解决这个问题?

澄清代码:

客户

var connection = new signalR.HubConnection('http://localhost:8956/testhub');
connection.on('onStart', function() {
    console.log('onStart');
  });

  connection.on('onEnd', function() {
    console.log('onEnd');
  })

  console.log('connection=', connection);

  connection.onClosed = function(error) {   // this gets fired
    console.log('connection closed');
    //setTimeout(function() {
    //  connection.start();
    //}, 10000);
  }

  connection.onReconnecting = function() {   // this not
    console.log('trying to reconnect');
  }

  connection.start();

服务器集线器“TestHub”

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AspNetCore.SignalR;
using System.Threading.Tasks;


namespace SignalRCoreConsole.Hubs
{
    class TestHub : Hub
    {
        public void Start()
        {
            Clients.All.InvokeAsync("onStart");
            Console.WriteLine("TestHub: Start");
        }

        public void End()
        {
            Clients.All.InvokeAsync("onEnd");
            Console.WriteLine("TestHub: End");
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            Console.WriteLine("client disconnected");
            return base.OnDisconnectedAsync(exception);
        }

        public override Task OnConnectedAsync()
        {
            Console.WriteLine("client connected");
            return base.OnConnectedAsync();
        }
    }
}

【问题讨论】:

    标签: javascript asp.net-core signalr asp.net-core-signalr


    【解决方案1】:

    Asp.NET Core 的 SignalR 没有重新连接。您在先前版本的 SignalR 的文档中查找了 onReconnecting,但新版本中不再存在该功能。看看announcement,它描述了两者之间更大的重大变化。

    【讨论】:

    • 谢谢。是否有处理断开连接的最佳做法?
    • 最简单的就是你所拥有的。不过,这不会处理丢失的消息...
    • "没有重新连接" ??为什么不呢,HubConnectionBuilder() 中的 .withAutomaticReconnect() 怎么样。
    • 当时不支持重新连接。另外,我的理解是即使现在重新连接也不允许识别和恢复客户端重新连接时丢失的消息。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 2017-01-19
    • 2011-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多