Use on .net core components of signalR

SignalR to provide a more convenient web interaction responsive to the push-based solution. With it later can achieve the client directly call the method server and return values ​​(the client can be a variety of platforms, currently SignalR supported languages ​​have C #, java, javaScript, nodejs, etc.), the server also can call the Client methods to achieve the original object becomes a single-pass double-pass through this way.

There is a very important concept in SignalR is the Hub, the Hub If you get the previous corresponding MVC architecture is the controller, the difference between them is that we need to register the Hub own route, and the controller is based on agreement of.

First create a Hub

 public class NewsPushHub:Hub
    {

    }

  This is a newsfeed Hub, it must inherit this base class to the Hub, Hub base class can also receive a generic implementation, the client's specification method can be used to this generic

  NewsPushHub class public: the Hub <IClientFuncs> 
    { 
        /// <Summary> 
        The method can be invoked /// client 
        /// </ Summary> 
        /// <param name = "MSG"> </ param> 
        /// <Returns> </ Returns> 
        public the Task DepartmentNotice the async (String MSG) 
        { 
            // this transmission method can only interface constraints 
            the await Clients.All.SendMsg (MSG); 
        } 
    } 
    /// <Summary> 
    /// defined the client listening process name 
    /// </ Summary> 
    public interface IClientFuncs 
    { 
        the Task the SendMsg (String MSG); 
    }

  

There are two ways this can be written directly call a client, but before the call to register first, before we Core3.0 is app.UseSignalR (hub => hub.MapHub <NewsPushHub> ( "/ SignalR / News ")) to register the access routes SignalR now changed all unified in app.UseEndpoints () method to register this extension, now in the Startup type the code like this
 
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllersWithViews();
            services.AddSignalR();
        }
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<NewsPushHub>("/SignalR/News");
                endpoints.MapControllerRoute("default", "{controller=Home}/{action=Index}/{id?}");
            }); 
          
        }

  In this which I configured the MVC includes middleware and dependency injection, in MVC 3.0 middleware and dependency injection has changed to become more specific, the route becomes unified set inside () This method UseEndpoints, inside it a delegate is a IEndpointRouteBuilder parameters, we can map various parameters by the routing configuration, there are a lot of map, where the purpose is to configure MVC and SignalR interaction. The following is the client's first need to install js code aspnet-signalr

// Create a matching http: localhost: 5000 / SignalRNews routing connections 
const Connection = new new signalR.HubConnectionBuilder () 
    .withUrl ( "/ SignalRNews") 
    .configureLogging (signalR.LogLevel.Information) 
    .build (); 
// start the connection this time will send a connection pending state 101 
connection.start () the then (function () {. 
    the console.log ( "connected"); 
}); 
// listening client server method call 
connection.on ( "SENDMSG", (MSG) => { 
    $ ( "dispaly-Message.") the append ( `<P> $ {MSG} </ P>`);. 
}); 

$ ( "# Submit") the Click (. = E> { 
    const = $ MSG ( "MSG #") Val ();. 
    // calls the service method ends DepartmentNotice 
    connection.invoke ( "DepartmentNotice", msg) .then (() =>{ 
        The console.log ( "transmission completion message");  
    });
})

  

 

 

 

 The above can be seen that the end result is achieved interworking between different messaging client  

In fact Signalr can also be injected, for example, usage dependency injection controller which then randomly push message directly in MVC

 

  public class HomeController:Controller
    {
        private readonly IHubContext<NewsPushHub> _hub;

        public HomeController(IHubContext<NewsPushHub> hub)
        {
            this._hub = hub;
        }
        public IActionResult Index()
        {
            _hub.Clients.All.SendAsync("Temp", "test");
            return View();
        }
       
       
    }

  From the above code injected seen out in the Home controller NewsPushHub the Hub as long as there is a Client Access Index interface will inform all clients

Summary: SignalR the original complex two-inefficient programming easier, Siganlr long as they support the mode 3 connection client and server (1, 2 long polling mode, the server 3 transmits an event, WebSocket) the most efficient course It is websocket but some of the browser is not supported;

demo code above address

Guess you like

Origin www.cnblogs.com/lvshunbin/p/11622758.html