代码之家  ›  专栏  ›  技术社区  ›  Alen Alex

调用信号器集线器对Asp.Net核心Web API不起作用

  •  3
  • Alen Alex  · 技术社区  · 6 年前

    我是个新手。我正在尝试设置一个Asp.Net核心WebAPI,以便其他客户端可以使用signaler连接到它并获取实时数据。

    public class TimeHub : Hub
    {
        public async Task UpdateTime(string message)
        {
            await Clients.All.SendAsync("ReceiveMessage", message);
        }
    }
    

    我的接力班如下:

    public class TimeRelay : ITimeRelay
    {
        private readonly IHubContext<TimeHub> _timeHubContext;
    
        public TimeRelay(IHubContext<TimeHub> context)
        {
    
            _timeHubContext = context;
            Task.Factory.StartNew(async () =>
            {
                while (true)
                {
                    await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());
                    Thread.Sleep(2000);
                }
            });
        }
    }
    

    启动类:

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    
        services.AddSignalR();
    }
    
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        app.UseDeveloperExceptionPage();
    
        app.UseHttpsRedirection();
    
        app.UseSignalR((x) =>
        {
            x.MapHub<TimeHub>("/timeHub");
        });
        app.UseMvc();
    }
    

    客户端是一个控制台应用程序,代码是:

    class Program
    {    
        static Action<string> OnReceivedAction = OnReceived;
    
        static void Main(string[] args)
        {
            Connect();
            Console.ReadLine();
        }
    
        private static async void Connect()
        {
            var hubConnectionBuilder = new HubConnectionBuilder();
    
            var hubConnection = hubConnectionBuilder.WithUrl("http://localhost:60211/timeHub").Build();
    
            await hubConnection.StartAsync();
    
            var on = hubConnection.On("ReceiveMessage", OnReceivedAction);
    
            Console.ReadLine();    
            on.Dispose();
            await hubConnection.StopAsync();
        }
    
        static void OnReceived(string message)
        {
            System.Console.WriteLine($"{message}");
        }
    }
    

    我试着调试应用程序。客户端连接到 TimeHub 很成功。中的连接数 Clients.All 当客户端连接时,从0更改为1。但是,当 await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString()); 执行时 UpdateTime 功能 时光枢纽

    我试着用 "UpdateTime" , "SendMessage" "ReceiveMessage" 方法 Clients.All.SendAsync TimeRelay 上课。什么都没用。有人能指出我在这方面的错误吗。

    2 回复  |  直到 6 年前
        1
  •  1
  •   Edward    6 年前

    为了 Clients ,如果没有客户端连接到服务器,则为空。用于启动 Asp.Net Core SignalR Console App 同时 客户 可能为空,因为 Index 可能在控制台应用程序连接信号服务器之前调用。

    尝试以下步骤:

    1. 改变 TimeHub

      public class TimeHub: Hub
      {
      public async Task UpdateTime(string message)
      {
          if (Clients != null)
          {
              await Clients.All.SendAsync("ReceiveMessage", message);
          }
      }
      }
      
    2. 时光枢纽

       services.AddSingleton<TimeHub>();  
      
    3. 控制器

       public class HomeController : Controller
      {
      private readonly TimeHub _timeHub;
      public HomeController(TimeHub timeHub)
      {
          _timeHub = timeHub;
      }
      public IActionResult Index()
      {
          Task.Factory.StartNew(async () =>
          {
              while (true)
              {
                  try
                  {
                      await _timeHub.UpdateTime(DateTime.Now.ToShortDateString());
                      Thread.Sleep(2000);
                  }
                  catch (Exception ex)
                  {
      
                  }
              }
          });
          return View();
      }
      
        2
  •  1
  •   Alen Alex    6 年前

    我想我会在这里回答的。谢谢@TaoZhou的提示。

    我的错误是从服务器发送“UpdateTime”并在客户端等待“ReceiveMessage”。

    理想情况下,代码应如下所示:

    信号服务器:
    await context.Clients.All.SendAsync("UpdateTime", DateTime.Now.ToShortDateString());

    信号客户端:
    var on = hubConnection.On("UpdateTime", OnReceivedAction);

    在这种情况下,从服务器发送的任何消息都将立即在客户端收到。
    有关详细信息,请参阅问题中提供的代码。