Asp. NET using SIGNALR to build a persistent connection between the browser and the server

Source: Internet
Author: User
Objective

The browser accesses the Web page through the HTTP protocol, the browser sends a request, and the server returns a result. The server is a passive receive request, if you want to reverse, the server actively send information to the browser do?

There are a number of workarounds, such as round robin (browser timed to the server asking for new data), WebSocket (HTML 5) ...

And SignalR is the combination of these technologies, it automatically identify the current browser support which way, and then choose the best way. We do not need to pay attention to these details in the development, SignalR will help us achieve, and SignalR is developed by Microsoft, easy to use is the consistent style.

Environment

. NET 4.5 and above, low No.

If the Visual Studio version is too low and has no SignalR, follow these steps to add:

Visual Studio's menu tool, library Package Manager, manage the NuGet packages for your solution (only after you open the solution), and search for "SignalR" in the Pop-up dialog box.

I use the Visual Studio 2013 is not required to manually add SignalR, itself comes with.

Actual combat

Open Visual Studio (my version is 2013) and build an ASP.

First step, add a "SignalR Permanent connection class"

Such as:

Once added, we can see that Visual Studio also automatically added some references to us, as well as the Scripts folder (which contains jquery.signalr-2.0.0.js). The initial code for this class is as follows:

public class myconnection1:persistentconnection{protected override Task onconnected (irequest request, String Connectio NId) {return connection.send (ConnectionID, "welcome!");}  protected override Task onreceived (irequest request, String ConnectionID, string data) {return Connection.broadcast (data ); }}

Step two, add "OWIN Startup class"

Then add the point code:

public class startup1{public void configuration (Iappbuilder app) {//For more information on how to configure an application, visit http://go.microsoft.com/ fwlink/? linkid=316888 app. Mapsignalr<myconnection1> ("/mypath"); MyPath is our casual writing. }}

MyConnection1 is the class name created in the first step.

Step three, add a "Web form"

<textarea id= "Info" cols= "ten" rows= "></textarea><script src=" Scripts/jquery-1.10.2.min.js "> </script><script src= "Scripts/jquery.signalr-2.0.0.min.js" ></script><script type= "text/ JavaScript "><!--var conn = $.connection ("/mypath ");  Conn.start (). Done (function (data) {  $ ("#info"). Append ("Successful connection, ConnectionID:" + data.id + "\ r \ n");});  Conn.received (function (data) {  $ ("#info"). Append ("Data received:" + + data + "\ r \ n"); /--></script>

The results are as follows:

Expand it.

MyConnection1:

Method onconnected: When a connection is created.

Method Onreceived: When the data submitted by the client is received, the parameter data is what it receives.

Method ondisconnected: When the connection is disconnected. It is not used on top.

Method onreconnected: When the connection is reconnected. It is not used on top.

......
MyConnection1 Properties of Connection:

Method send: Sends data to the browser, the first parameter is ConnectionID (string type), and the second parameter is the data to be sent.

Method Broadcast: Send data to all browsers (exactly all connections).

Js:

var conn = $.connection ("/mypath"); Creates a connection object.

Conn.start (). Done () Start () is the code to be executed after the success of the Connect, done () connection.

Conn.received () is the data sent by the server to be executed.

Conn.send () is sending data to the server. It is not used on top.

Let's look at a more complete code:

This is not to say that some methods are not used, the following example is more complete:

MyConnection1:

protected override Task onconnected (irequest request, String ConnectionID) {return connection.send (ConnectionID, " Welcome! ");} protected override Task onreceived (irequest request, String ConnectionID, String data) {Connection.send (ConnectionID, " I received: "+ data"; Return Connection.broadcast ("All Attention: I received the data from the client.") ");}

Code for WEB forms:

<textarea id= "Info" cols= "rows=" ></textarea> messages to be sent to the server: <input type= "text" id= "MSG" size= "20"/ ><input type= "button" value= "Send Message" onclick= "Javascript:conn.send ($ (' #msg '). Val ());"/><script src= " Scripts/jquery-1.10.2.min.js "></script><script src=" Scripts/jquery.signalr-2.0.0.min.js "></ Script><script type= "Text/javascript" ><!--var conn = $.connection ("/mypath");  Conn.start (). Done (function (data) {  $ ("#info"). Append ("Successful connection, ConnectionID:" + data.id + "\ r \ n");});  Conn.received (function (data) {  $ ("#info"). Append ("Data received:" + + data + "\ r \ n"); /--></script>

So far, everyone may not be interested in, the server actively send data where???

We are now doing a timed program where the server periodically sends data to the browser.

New Global.asax (Global Application Class) (not to say that the code can only run in Global.asax, we just put it here for testing timed execution).

Add the following code:

protected void Application_Start (object sender, EventArgs e) {Timer timer = new timer (); timer. Elapsed + = timer_elapsed; Timer. Start ();} void Timer_elapsed (object sender, Elapsedeventargs e) {var context = GlobalHost.ConnectionManager.GetConnectionContext <MyConnection1> (); Context. Connection.broadcast ("I am active in" + DateTime.Now.ToString () + "send data to the browser. ");}

The effect is as follows:

The above code, we use the context. Connection.broadcast, if it is for a connection to send, then use the Send method, which requires ConnectionID, but to choose which ConnectionID is the business level, not the problem.

Summarize

The above is the entire content of this article, I hope that the content of this article on everyone's study or work can bring certain help, if there is doubt you can message exchange.


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.