This article is mainly in my beginning to learn the technical summary of SignalR , online looking for learning methods and examples are mostly just translated an example of the official, and did not give some other examples of classic cases, so this article summarizes, I in the implementation of push simple data, Think of how to push the complex data, as well as push a real-time chart data, text for my original, reproduced please indicate the source: richard.hu, first on a bunch of messy instructions first:
The official address of SignalR is: https://www.asp.net/signalr
The online example is a chat example, the official website address is: https://docs.microsoft.com/en-us/aspnet/signalr/overview/getting-started/ Tutorial-getting-started-with-signalr
What does an example of chatting mean, is that after any one browser client sends the data to the server, the server receives the data and then mass it to everyone. This is really a classic example, so this time my research does not consider this situation, consider another classic case, called real-time data push. What this means is that your system has some real-time data that needs to be displayed on the client side without SignalR , ASP. NET basically can only through the constant Ajax polling refreshes the data, both the server side and the client, will bring great performance test.
Well, to start today's learning journey, I rely on the development environment that is visual Studio 2017, if not the IDE, not guaranteed to be completely correct.
1. Create an ASP. NET MVC Project without authentication
This completes the first step and creates a project.
2. Install the SIGNALR component and install it in NuGet mode
Installation of the process there is nothing to say, is all the way without brain installation can be, after the installation has appeared the interface description, this note is worth looking at, the original is as follows:
Please see http://go.microsoft.com/fwlink/? linkid=272764 for more information on using the signalr.upgrading from 1.x to 2.0-------------------------. See Http://go . microsoft.com/fwlink/? linkid=320578 For more information on what to upgrade your SignalR 1.x application to 2.0.Mapping the Hubs connection------ ----------------------to enable SignalR in your application, create a class called Startup with the following:using Micros Oft. Owin;using owin;using mywebapplication;namespace mywebapplication{public class Startup {public void Configu Ration (Iappbuilder app) {app. MAPSIGNALR (); }}} Getting Started---------------see http://www.asp.net/signalr/overview/getting-started For more information on how To get started. Why does ~/signalr/hubs return 404 or what do I get a JavaScript error: ' Myhub is undefined '?------------------------------ --------------------------------------------------------------This issue are generally due to a missing or invalidScript reference to the auto-generated Hub JavaScript proxies at ' ~/signalr/hubs '. Please make sure, the Hub route is registered before any and routes in your application. In ASP 4 You can do the following: <script src= "~/signalr/hubs" ></script> If you ' re writing an A Sp.net MVC 3 Application, make sure, is using url.content for your script references: <script src= "@Url. Co Ntent ("~/signalr/hubs") "></script> If you ' re writing a regular ASP. Application use Resolveclienturl for your Script references or register them via the ScriptManager using a app root relative path (starting with a ' ~/'): <s Cript src= ' <%: Resolveclienturl ("~/signalr/hubs")%> ' ></script> If the above still doesn ' t work, your may ha ve an issue with Routing and extensionless URLs. To fix this, ensure you has the latest patches installed for IIS and ASP.
Read carefully, the inside said a lot of things, I first roughly say, and so on after all the demonstration, and then come back to see the impressive:
1. Map The hubs connection, you need to create a startup class, and paste the above code
2. There is a SIGNALR automatically generated proxy hub, in the path ' ~/signalr/hubs ' inside, and then the ASP. NET MVC5 need to use
<script src= "~/signalr/hubs" ></script>
There is nothing else, and the next step is to transform the project.
3. Retrofit index.cshtml File
Our purpose is clear, here to show the server push data, it is easy to deal with, the other a lot of things are not
@{ viewbag.title = "Home page";} <div id= "Test" > here will show the data pushed by the server </div>
This time you can try to run a
Emmmmmmmmm, talking about a bunch of mistakes, it's okay, so just look at what's wrong,
1. No Owinstartupattribute attribute
2. No Startup.cs class
That's not what we mentioned in the second step, so let's just do what he says.
4. Create a Startup.cs file
We create a class file, where it is placed below the project, and then copy the code
Then, paste the following code, anyway, that's what the authorities are asking.
Using system;using system.collections.generic;using system.linq;using system.web;using Microsoft.Owin;using Owin; [Assembly:owinstartup (typeof (Webapplication1.startup))]namespace webapplication1{public class Startup { c2/>public void configuration (Iappbuilder app) { //For more information on how to configure an application, visit http://go.microsoft.com/fwlink/? linkid=316888 app. MAPSIGNALR ();}}}
Then we run to see the effect:
Haha, see can, and then prepare the real data push.
4. Create a MyHub.cs file
We create a folder, hubs and then add a file, named MyHub.cs
Then copy the following code in:
Using microsoft.aspnet.signalr;using microsoft.aspnet.signalr.hubs;using newtonsoft.json.linq;using System;using System.collections.generic;using system.linq;using system.threading;using System.web;namespace webapplication1.hubs{[Hubname ("Myhub")] public class Myhub:hub {//are set via the constructor on EAC H creation private broadcaster _broadcaster; Public Myhub (): This (broadcaster.instance) {} public Myhub (broadcaster broadcaster) {_broadcaster = broadcaster; }}///<summary>//Data Broadcaster///</summary> public class broadcaster {private readonl Y static lazy<broadcaster> _instance = new Lazy<broadcaster> (() = new broadcaster ()); Private ReadOnly Ihubcontext _hubcontext; Private Timer _broadcastloop; Public broadcaster () {//Get all connected handles, conveniently followed by message broadcast _hubcontext = Globalhost. Connectionmanager.gethubcontext<myhub> (); Start the broadcast loop _broadcastloop = new Timer (Broadcastshape, NULL, 1000, 1000); Private random random = new random (); private void Broadcastshape (object state) {//Method for periodic execution} public static broadcaster Insta nce {get {return _instance. Value; } } }}
It already contains a hub hub, and then set up a unified static broadcaster data broadcast object, and then we have to operate in the private void Broadcastshape (object state) method to operate it, Now we're going to push a random number, a random number of 0-1000, and then how to write the method, refer to the following
private void Broadcastshape (object state) { //method _hubcontext.clients.all.sendtest1 (random) executed periodically. Next (1000). ToString ()); }
OK, then we have finished the server, the next to be displayed on the client, go back to the index.cshtml page to see
@{ viewbag.title = "Home page";} <div id= "Test" > here will show the server push data </div> @section scripts { <script src= "~/scripts/ Jquery.signalr-2.2.3.min.js "></script> <script src=" ~/signalr/hubs "></script> < Script> $ (function () { var mypush = $.connection.myhub; Mypush.client.sendTest1 = function (message) { $ ("#test"). Text (message); Console.log (message); }; $.connection.hub.start (); }); </script>}
Here the two JS library must be referenced, especially the second one, the previous document is already explained, the following JS code is to get the hub agent, and then bind the message. Then you can run it.
Can see that this value is indeed changed, we then click on the F12 to see what is inside, found that there is indeed a hubs.js file exists, which contains the Myhub agent.
5. Push JSON data
The above has shown a push string operation, if we want to push a complex data to do, we have a badge display as an example
The code for the server:
private void Broadcastshape (object state) { Jobject json = new Jobject (); Json. ADD ("A", random. Next (1000, 10000). ToString ()); Json. ADD ("B", random. Next (20). ToString ()); Method _hubcontext.clients.all.sendtest1 (JSON) that is performed on a regular basis ; }
index.cshtml Code
@{ viewbag.title = "Home page";} <button class= "btn btn-primary" type= "button" id= "Test1" > Messages <span class= "badge" id= "Test2" >4 </span></button> @section Scripts { <script src= "~/scripts/jquery.signalr-2.2.3.min.js" >< /script> <script src= "~/signalr/hubs" ></script> <script> $ (function () { var Mypush = $.connection.myhub; Mypush.client.sendTest1 = function (JSON) { $ ("#test1"). HTML (JSON. A + ' <span class= "badge" > ' + JSON. B + ' </span> '); Console.log (message); }; $.connection.hub.start (); }); </script>}
And then run and discover:
It's not enough to find this, I want to show the chart dynamically, such as column chart
6. Real-Time Column chart
Column Chart plug-in We choose Open Source Echart chart, Baidu's works, very to force, official website address: http://echarts.baidu.com/Below casually put point this plug-in diagram example
We download this JS file,
Then add this JS file to the project, as follows
Then modify the server's Push method
private void Broadcastshape (object state) { int[] values = new INT[10]; for (int i = 0; i < values. Length; i++) { Values[i] = random. Next (+); } The method of regular execution _hubcontext.clients.all.sendtest1 (values); }
Modifying the client's index.cshtml code
@{viewbag.title = "Home page";} <div id= "test" style= "height:600px" ></div> @section scripts {<script src= "~/scripts/ Jquery.signalr-2.2.3.min.js "></script> <script src=" ~/scripts/echarts.min.js "></script> < Script src= "~/signalr/hubs" ></script> <script> $ (function () {var myChart1 = echarts. Init (document.getElementById (' Test ')); Mychart1.setoption ({title: {text: ' Live data Load sample '}, tooltip: {}, Legend: {data: [' Sales ']}, Xaxis: { Data: ["shirts", "wool", "chiffon", "trousers", "high heel", "socks", "sleeves", "collars", "socks", "Brains"]}, YAxis: {}, Series: [{name: ' Sales ', type: ' Bar ', data: [] }] }); var mypush = $.connection.myhub; Mypush.clieNt.sendtest1 = function (array) {Mychart1.setoption ({series: [{ Data:array}]}); Console.log (array); }; $.connection.hub.start (); }); </script>}
Then you can run the program to see the desired effect.
Can read the dynamic changes in the chart data, the other dynamic chart is similar, the reference to this can be achieved, the idea is consistent. The text is here. If in doubt can add QQ Group: 592132877 or direct mail [email protected]
C # ASP. NET MVC SignalR learning real-time data push display with Echarts push live chart