ASP. NET MVC3 using SignalR for push (connect)

Source: Internet
Author: User

One, persistent Connection Example Tutorial 1, Implementing server-side code
1), write the server persistentconnection code

Create the PersistentConnection.cs file in the SignalR directory in the project

Using system;using system.collections.generic;using system.threading.tasks;using signalr;namespace signaltutorial.signalr{public class Myconnection:persistentconnection {protected override Task Onconnecte  Dasync (irequest request, String ConnectionID) {return connection.broadcast ("Connection" + ConnectionID        + "Connected");        } protected override Task Onreconnectedasync (irequest request, ienumerable<string> groups, String clientId)        {return Connection.broadcast ("Client" + clientId + "re-connected"); } protected override Task Onreceivedasync (irequest request, String ConnectionID, string data) {V AR info = data + ".            ConnectionID is ["+ ConnectionID +"] ";               Return Connection.send (ConnectionID, info);           Broadcast data to all clients return Connection.broadcast (info); } protected override Task Ondisconnectasync (string ConnectionID)        {return Connection.broadcast ("Connection" + ConnectionID + "disconncted"); } protected override Task Onerrorasync (Exception error) {return connection.broadcast ("Error ocur        Red "+ error); }    }}

1,myconnection inherits from the Persistentconnection, so that we can handle the processing in the case of client connection, reconnection, disconnection, sending of messages and connection errors. As you can see from the Persistentconnection interface below, Persistentconnection also supports groups for push.


2, the push message is provided by the Persistentconnection property Connection, which inherits from the Iconnection interface, which provides two functions for push and broadcast to a specific client.

System.Threading.Tasks.Task Send (String signal, object value)
System.Threading.Tasks.Task broadcast (object value)

2), configure access routing

In order to support client access, we will configure the routing table. Open Global.asax.cs and modify the Application_Start () function as follows:

protected void Application_Start () {    arearegistration.registerallareas ();    Routetable.routes.mapconnection<myconnection> ("echo", "echo/{*operation}");    Registerglobalfilters (globalfilters.filters);    RegisterRoutes (routetable.routes);    Make connections wait 50s maximum for any response. After    //50s is up, trigger a timeout command and make the client reconnect.    GlobalHost.Configuration.ConnectionTimeout = Timespan.fromseconds (a);    Disconnecttimeout     //heartbeatinterval     //keepalive}

In the above code, I mapped the access of ECHO and its sub-paths to myconnection and set the connection time-out to. Here you can also set some other parameters, such as the disconnection time-out period, heartbeat interval and so on.

2, implementing client code
@model dynamic@{    viewbag.title = "Title";} <script src= "@Url. Content (" ~/scripts/persistent.js ")" Type= "Text/javascript" ></script>

2), write Javascript

add a new Scripts to the Javescript directory Script: Persistent.js. The contents are as follows:

$ (function () {var myclientname = $ (' #Placeholder '). Val ();    var connection = $.connection ('/echo ');        Connection.received (function (data) {var msg = new String (data);        var index = msg.indexof ("#");        var clientName = msg.substring (0, index);        var content = msg.substring (index + 1); if (ClientName = = NULL | | clientName = = "") {writeEvent (' <b> ' + ' system message ' + ' </b>: ' + content, ' even        T-message ');        } else {writeEvent (' <b> ' + clientName + ' </b> said to everyone: ' + content, ' event-message ');    }    });    Connection.start ();        $ ("#broadcast"). Click (function () {var msg = myclientname + "#" + $ (' #msg '). Val ();    Connection.send (msg);    });        A function to write events to the page function writeEvent (EventLog, Logclass) {var now = new Date ();        var nowstr = now.gethours () + ': ' + now.getminutes () + ': ' + now.getseconds (); $ (' #messages '). Prepend (' <li class= "' +Logclass + ' ><b> ' + nowstr + ' </b> ' + eventLog + ' .</li> '); }});

1, when creating the connection, the specified path is "/echo", the path on the server side of the route map table is mapped to myconnection, so this connection is pointed to the myconnection provided earlier.

2, put the ClientName information into the message and use # to concatenate the ClientName and the message content into a single MSG.


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.