📜 ⬆️ ⬇️

ASP.NET Push notifications with SignalR

As an example, we will write a primitive chat with instant notification of all customers using the SignalR library .


training


To do this in Visual Studio we will create an empty ASP.NET project Empty Web Application

The SignalR library itself is added to one line via NuGet:
')
Install-Package SignalR
This will add jQuery and SignalR scripts to the project, as well as a reference link to the SignalR dll and other dlls necessary for its work.

write server code



Add an arbitrary class - I will call it Chat, it must inherit from the Hub class defined in SignalR.Hubs

 public class Chat : Hub { public void Send(dynamic message) { Clients.AddChatMessage(message); } } 


In our class, you can define any number of any public methods, with any parameters - all of them are available from the appropriate JavaScript proxy class on the client.

In our case, we define a simple Send, and for convenience, the parameter will be dynamic.

Clients defined in the parent class, is a dynamic object — a call to any arbitrary method on it — calls it on all connected clients with the same parameters.

write client code



we add to the html project a document - chat.html, with a simple markup

 <input type="text" id="msg" /> <input type="button" id="broadcast" value="broadcast" /> <ul id="messages"> </ul> 


We add links to the necessary JS scripts, while / signalr / hubs should be added after signalr.js, as it depends on it.

 <script src="http://code.jquery.com/jquery-1.7.min.js" type="text/javascript"></script> <script src="/Scripts/jquery.signalR.min.js" type="text/javascript"></script> <script src="/signalr/hubs" type="text/javascript"></script> 


then the client script itself:

 <script type="text/javascript"> $(function () { //    var chat = $.connection.chat; // ,    , //    chat.AddChatMessage = function (msg) { $("#messages").append("<li>" + msg.name + " : " + msg.text + "</li>"); }; //  -        $("#broadcast").click(function () { var msg = { 'name': $.browser.version, 'text': $('#msg').val() }; chat.send(msg); }); //   $.connection.hub.start(); }); </script> 


I used browser version for each client name.

as a result



All clients receive push-style notifications at the same time, as seen in the video:


instead of conclusion



you can get some examples of using SignalR
Install-Package SignalR.Sample

Download the source code of the example reviewed in the article and in the video - here

Happy New Year 2012!

Source: https://habr.com/ru/post/135604/


All Articles