Home .NET SignalRCore.«Hello Habr!»

SignalRCore.«Hello Habr!»

by admin

Briefly : a small self-contained example illustrating SignalR for .NET Core 2 and development in the IDE Rider At the very end is a video Dino Esposito from the conference DotNext On the same topic.

Everyone is used to push notifications in the browser. However, creating them requires a certain amount of experience and willingness on the part of the programmer to mess around with websockets and other front-end stuff that allows a web application to send updates to the browser client at the right time. Moreover, websockets don’t always work well, so you have to create code to support multiple transports – that kind of thing has to be thought about and debugged well.

Obviously, there are off-the-shelf libraries that take care of this. In the ASP.NET world of web applications, this is SignalR; it allows the developer to abstract away the above complexities and use a simple software model to handle push notifications.

SignalRCore.«Hello Habr!»

SignalR makes it possible to implement the "publisher-subscriber" model on the server side. Clients, which are usually (though not necessarily) web pages, subscribe to a so-called hub, and it, in turn, can send them updates. It’s like in Habra – you go to the .NET hub, subscribe, hawk in the comments 🙂

The updates that come to us can either be sent at any time (look at the page with comments: the server sends the browser client a fresh comment – and the page immediately shows the comment to the user), or triggered by a message from the client (someone pressed the "update all" button – not the browser one, but in the Hubinterface).

The old SignalR, however, is not compatible with ASP.NET Core. So if you wanted to use push notifications in a web application, you had to find some other ways before. Last fall, two alpha versions of SignalR Core (or more correctly: "SignalR for ASP.NET Core 2.0") were released and hopefully soon Microsoft will show us the beta and then the release.

In order to honestly describe the whole model of programming such applications, we need to write a series of posts. Let’s start with something simple: let’s try a simple server hub and an equally simple JavaScript-client which will transmit a message "A UFO has flown in and left this message".

Server

This is happening on SignalR Core alpha 2 for ASP.NET Core 2. The IDE used is Jetbrains Rider , because it is cool!

Let’s start by creating an empty application (.NET Core/ASP.NET WebApplication):

SignalRCore.«Hello Habr!»

This project template will already contain the package Microsoft.AspNet.All , and everything you need to run is there. Basically, you can press the start button right away and the application will work.

You need to install the NuGet package for SignalR. Note that you must now use the checkbox PreRelease (which will in turn add the option -Pre in NuGet), since we are dealing with pre-release :

SignalRCore.«Hello Habr!»

Next, we add a Hub. We create a new class :

public class HabrDotNetHub : Hub{public Task BroadcastNlo(){return Clients.All.InvokeAsync("nlo");}}

In SignalR Core, the class that inherits from Hub , is capable of communicating with clients subscribed to it. The communication can take several forms: broadcasting to "all clients", "to all but one", sending to a single client or sending to a specific group. In our case, we broadcast the message "nlo" to all clients.

In class Startup we need to remove the default "Hello world" code and register our hub. We get something like :

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 which will be used to reach our hub from the client side. To return statics (HTML and JavaScript) we use UseFileServer()

You need to check that it starts. If it doesn’t, it’s a problem, you need to fix it.

Client

In order for the web page to communicate with our hub, we’ll need a couple of scripts. We could do this manually, but let us have the npm Of course, it needs to be pre-installed (it goes included with Node.js ). The console is already built into Rider, so you have to open it, go to the wwwroot and run the following commands :

npminstall @aspnet/signalr-clientnpm install jquery

SignalRCore.«Hello Habr!»

The first package is the JavaScript client for SignalR Core (the most recent version of the file today is called signalr-client-1.0.0-alpha2-final.js ). The second package is the jQuery library, which, although no longer required by SignalR Core, makes life a lot easier when working with frontend code. You can copy signalr-client-1.0.0-alpha2-final.js and jquery.js into the folder wwwroot but I’m lazy, let it stay exactly as it was generated by npm

Then we create in the directory wwwroot index.html Add to it links to the above scripts, a placeholder for messages (in our example its ID would be "log"), and a little 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("a ufo flew in and left this message <br />");});connection.start().then(() => connection.invoke('BroadcastNlo'));});</script></head><body><div id="log"> </div></body></html>

This JavaScript code establishes a connection to the hub, registers a callback to receive the "nlo" message, and calls the BroadcastNlo() Hub. We try :

SignalRCore.«Hello Habr!»

Great! The connection is established and we get something back from the server (i.e. the hub). Let’s open a couple more browser windows to the same endpoint :

SignalRCore.«Hello Habr!»

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 state on the server, the messages are simply added to the text the clients already have. Clients who connect later (and thus miss some of the old messages) receive and show us fewer messages on the screen.

Panem et circenses!

This is not another technology from Microsoft, the subtitle translates merely as "Bread and circuses!" With bread, taking the above example with the forwarding "nlo" as it is, we seem to have sorted it out, now let’s look at something more beautiful.

In official repository with examples for ASP.NET Core SignalR has a pretty good ready-made project called "WhiteBoard". It’s a fairly simple and minimalistic web-based implementation of a whiteboard, where all clients see in their browsers what they drawon the page with their mouse (or finger, if the example races on a touch device), together with other clients. You can look at the code and see that it’s written favorably beautifully and succinctly compared to the classic web chat design.

The depicted picture is passed as a set of segments (more precisely, coordinates of points between which segments are to be drawn). Obviously, the information we have will not be the test string as entered by the user, but the coordinates of the manipulator.

Next, the hub does not send messages to all clients (as in the case of our simplest chat), but to everyone except which sends the information (hence AllExcept), because the sending client already knows the coordinates (and, generally speaking, has already drawn another segment for itself).

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 their users’ drawn segments so :

connection.invoke('draw', last_mousex, last_mousey, mousex, mousey, clr);

where draw – the route to the registered DrawHub.

Here we see ASP.NET Core SignalR taking on the rather routine task of transmitting a set of data, not just a text string. All we have to do is use that data properly on the receiving end. It hides a lot of trivia well under the hood, allowing us to keep our heads clear of all the low-level complexities. So, let’s run the example, arm ourselves with a stylus (or, like me, a mouse), and try our hand:

SignalRCore.«Hello Habr!»

For a further dive into the topic, check out Dino Esposito’s talk from the DotNext 2016 conference:

A moment of publicity. As you probably know, we do conferences. The closest conference about .NET is DotNext Piter 2018. to be held on April 22-23, 2018. You can go there and talk to the developers of various modern technologies, including a lot about .NET Core (read more in the conference program ). In short, come on in, we’re waiting for you.

You may also like