In short: a small self-sufficient example illustrating SignalR for .NET Core 2 and development in IDE Rider . At the very end - a Dino Esposito video from the DotNext conference on the same topic.
Everyone is used to browser push notifications. However, creating them requires a certain amount of experience from the programmer and a desire to mess around with web-based software and other front-line problems that allow the web application to send updates to the browser client at the right time. Moreover, not always do webboxes work well, so you have to create code to support several transports — you need to think about such a thing and debug it well.
Obviously, there are ready-made libraries that take it upon themselves. In the world of ASP.NET web applications, this is SignalR, it allows the developer to ignore the listed difficulties and use a simple program model for working with push notifications.
SignalR makes it possible to implement the publisher-subscriber model on the server side. Clients, who usually (though not necessarily) are web pages, subscribe to the so-called hub (hub), and he, in turn, can send them updates. Everything is like on Habré - we run into the .NET hub, subscribe, haytim in the comments :)
Updates arriving to us can be sent at any time (take a look at the comments page: the server sends a fresh comment to the browser client that just appeared - and the page immediately shows the comment to the user), or caused by a message from the client (someone gave the “update” button). all ”- not browser-based, but in the Habra interface).
Old SignalR, however, is not compatible with ASP.NET Core. Therefore, if you wanted to use push notifications in a web application, you had to look for other ways before. In the autumn of last year, two alpha versions of SignalR Core (more correctly, “SignalR for ASP.NET Core 2.0”) were released, and hopefully Microsoft will soon show us the beta, and then the release.
To honestly describe the entire programming model of such applications, you need to write a series of posts. Let's start with something simple: let's try a new technology using the example of a bundle of unpretentious server hub and a no less simple JavaScript client that will transmit the message “UFO arrived and left this message”.
It happens on SignalR Core alpha 2 for ASP.NET Core 2. Jetbrains Rider is used as IDE, because it is cool!
First, create an empty application (.NET Core / ASP.NET WebApplication):
In this project template, there will already be a Microsoft.AspNet.All
package, and everything you need to run is there. In principle, you can immediately push the application launch button, and it will work.
You must install the NuGet package for SignalR. Please note that now you need to use the PreRelease
(which in turn will add the -Pre
option to NuGet), since we are dealing with a pre-release:
Next, add a hub. Create a new class:
public class HabrDotNetHub : Hub { public Task BroadcastNlo() { return Clients.All.InvokeAsync("nlo"); } }
In SignalR Core, a class that inherits from Hub is able to communicate with clients subscribed to it. Communication can take place in several ways: broadcast to “all clients”, “to all but one”, send to a single client, or send to a specific group. In our case, we will broadcast the message "nlo" to all clients.
In the Startup class, we need to remove the default “Hello world” code and register our hub. It turns out something like this:
public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } app.UseFileServer(); app.UseSignalR(routes => { routes.MapHub<HabrDotNetHub>("nlo"); }); } }
In UseSignalR()
we register the route by which our hub will be available from customers. To return statics (HTML and JavaScript) is UseFileServer()
.
It is necessary to check that it starts. If not - this is a problem, you need to repair.
In order for a web page to communicate with our hub, you will need a couple of scripts. It would be possible to do this manually, but let npm trample on us. Of course, you need to install it in advance (it comes with Node.js ). The console is already built into Rider, so you need to open it, go to the wwwroot
folder and execute the following commands:
npm install @aspnet/signalr-client npm install jquery
The first package is a JavaScript client for SignalR Core (the most recent version of the file today is signalr-client-1.0.0-alpha2-final.js ). The second package is the jQuery library, which, although no longer required for SignalR Core, but when working with code for the frontend, makes life much easier. You can copy signalr-client-1.0.0-alpha2-final.js and jquery.js to the wwwroot folder, but I'm lazy, let everything remain exactly the way it was generated by npm
.
Next, create the index.html file in the wwwroot directory. We add links to the above scripts, a placeholder for messages (in our example, its ID is "log"), and a small script to make it all work together:
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title>Hello SignalR Core!</title> <script src="node_modules/jquery/dist/jquery.js"></script> <script src="node_modules/@aspnet/signalr-client/dist/browser/signalr-client-1.0.0-alpha2-final.js"></script> <script type="text/javascript"> $(document).ready(function () { var connection = new signalR.HubConnection('/nlo'); connection.on('nlo', data => { $("#log").append(" <br />"); }); connection.start() .then(() => connection.invoke('BroadcastNlo')); }); </script> </head> <body> <div id="log"></div> </body> </html>
This JavaScript code establishes a connection with the hub, registers a callback to receive the message "nlo" and calls the hub's BroadcastNlo()
method. We try:
Fine! The connection is established, and we receive something in response from the server (i.e. the hub). Open a couple more browser windows to the same endpoint:
Here you can see that, as we open new windows, the message "nlo" is broadcast to all connected clients. Since we don’t store any status on the server, messages are simply added to the text already present in the clients. Clients who connect later (and thus missed some of the old messages) receive and show us fewer messages on the screen.
This is not another technology from Microsoft, the subtitle translates only as "Bread and circuses!" With bread, taking the above example with the shipment of "nlo", we seem to understand, now let's look at something more beautiful.
In the official repository with examples for ASP.NET Core SignalR there is a good ready-made project called “WhiteBoard”. This is a fairly simple and minimalistic web implementation of a meeting board, where all clients see in their browsers what they draw on the page with a mouse (or with a finger, if they run an example on a touch device), together with other clients. You can look at the code and see that it is written favorably beautifully and concisely, compared with the classic design of the web chat.
The displayed image is transmitted as a set of segments (more precisely, the coordinates of the points between which the segments should be drawn). Obviously, the information we will have is not the test string as entered by the user, but the coordinates of the manipulator.
Further, the hub sends messages not to all clients (as is the case with our simplest chat), but to everyone except for transmitting information (hence AllExcept), because the sending client already knows the coordinates (and, generally speaking, has already drawn another interval).
using Microsoft.AspNetCore.SignalR; using System.Collections.Generic; using System.Threading.Tasks; namespace WhiteBoard.Hubs { public class DrawHub : Hub { public Task Draw(int prevX, int prevY, int currentX, int currentY, string color) { return Clients.AllExcept(new List<string> { Context.ConnectionId }).InvokeAsync("draw", prevX, prevY, currentX, currentY, color); } } }
In turn, clients (each web page) send data about the segments drawn by their users as follows:
connection.invoke('draw', last_mousex, last_mousey, mousex, mousey, clr);
where draw is a route to the registered hub DrawHub.
Here we see how ASP.NET Core SignalR takes on the rather routine task of transferring a dataset, and not just a text string. We only need to use this data properly on the receiving side. He hides quite a lot of little things under the hood, allowing him not to bother with his very low-level difficulties. So we run an example, arm ourselves with a pen (or, like me, a mouse) and try our strength:
For further immersion in the topic, see the Dino Esposito report from the DotNext 2016 conference:
Minute advertising. As you probably know, we do conferences. The upcoming conference about .NET - DotNext Piter 2018 , which will be held April 22-23, 2018. You can come there and chat live with developers of various modern technologies, including there will be a lot of about .NET Core (written in more detail in the conference program ). In short, come in, we are waiting for you.
Source: https://habr.com/ru/post/349096/
All Articles