SignalR集线器可以接收来自客户端的事件吗?如果是这样,怎么办?

时间:2019-05-24 12:25:28

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

我有一个signalR集线器,它需要能够从客户端接收事件,然后通知连接到该集线器的所有其他客户端。

有可能吗?

我希望我的“集线器”应用程序能够接收和发送消息。我只能弄清楚如何发送消息。这是我现在拥有的:

应用程序1--集线器

启动类:

  public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSignalR().AddHubOptions<EventsHub>(options =>
            {
                options.HandshakeTimeout = TimeSpan.FromMinutes(5);
                options.EnableDetailedErrors = true;
            });
            services.AddTransient(typeof(BusinessLogic.EventsBusinessLogic));          
        }

        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });

            app.UseSignalR((configure) =>
            {
                configure.MapHub<EventsHub>("/hubs/events", (options) =>
                {
                });
            });          
        }

在应用程序1中设置集线器

 public class EventsHub : Hub
    {
        public EventsHub()
        {
        }

        public override Task OnConnectedAsync()
        {
            if (UserHandler.ConnectedIds.Count == 0)
            {
                //Do something on connect
            }
            UserHandler.ConnectedIds.Add(Context.ConnectionId);
            Console.WriteLine("Connection:");
            return base.OnConnectedAsync();
        }

        public override async Task OnDisconnectedAsync(Exception exception)
        {
          //Do something on Disconnect

        }


        public static class UserHandler
        {
            public static HashSet<string> ConnectedIds = new HashSet<string>();
        }
    }

BusinessLogic:


    public class EventsBusinessLogic
    {
        private readonly IHubContext<EventsHub> _eventsHub;

        public EventsBusinessLogic(IHubContext<EventsHub> eventsHub)
        {
            _eventsHub = eventsHub;                       
        }

        public async Task<Task> EventReceivedNotification(ProjectMoonEventLog eventInformation)
        {
            try
            {             
                 await _eventsHub.Clients.All.SendAsync("NewEvent", SomeObject);        
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }
        }
    }


在第二个应用程序中,该应用程序侦听来自中心的事件或消息:

Startup.cs

  private static void ConfigureAppServices(IServiceCollection services, string Orale, string Sql)
        {
            services.Configure<CookiePolicyOptions>(options =>
            {
                options.CheckConsentNeeded = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            //set up of singletons and transients

            services.AddHostedService<Events.EventingHubClient>();
        }

ClientHub连接到应用程序1:

public class EventingHubClient : IHostedService
    {
        private HubConnection _connection;

        public EventingHubClient()
        {

            _connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:61520/hubs/events")
                .Build();


            _connection.On<Event>("NewEvent",
    data => _ = EventReceivedNotification(data));

        }

        public async Task<Task> EventReceivedNotification(Event eventInformation)
        {
            try
            {


              //Do something when the event happens     

                return Task.CompletedTask;
            }
            catch (Exception e)
            {

                throw new Exception(e.Message);
            }

        }


        public async Task StartAsync(CancellationToken cancellationToken)
        {
            // Loop is here to wait until the server is running
            while (true)
            {
                try
                {
                    await _connection.StartAsync(cancellationToken);
                    Console.WriteLine("Connected");
                    break;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    await Task.Delay(100);
                }
            }
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            return _connection.DisposeAsync();
        }

    }

这可行,但是现在我希望应用程序2能够向应用程序1发送消息?因此,我需要与application2中的EventsBusinessLogic类类似的代码段才能将消息发送到应用程序1。

我希望这足够清楚了吗?这是SignalR的目的吗?

1 个答案:

答案 0 :(得分:0)

请参阅signalR文档signalR documentation for .net client

我猜你的Hub方法是这样的

public async Task SendTransaction(Transaction data)
{
    await Clients.All.SendAsync("TransactionReceived", data);
}

然后在客户端添加方法

在构造函数中添加

 connection.On<Transaction>("TransactionReceived", (data) =>
    {
        this.Dispatcher.Invoke(() =>
        {
           var transactionData = data;
        });
        });

然后在服务器上需要SendTransaction

private async void SendTransaction(Transaction data)
{
    try
    {
        await connection.InvokeAsync("SendTransaction", data);
    }
    catch (Exception ex)
    {                
        // 
        throw
    }
}