SIGNALR an integrated client and server library. Internal two object classes: Persistentconnection and Hub

Source: Internet
Author: User

SignalR encapsulates the behavior of the entire exchange of information, the client and server all use JSON to communicate, the server-side declaration of all hub information, will generally generate JavaScript output to the client.

It is a browser-based client and an ASP. NET-based server component that can be used for bidirectional multi-step dialogs with SIGNALR.  That is, the dialog can be unrestricted for a single stateless request/response data exchange; It will continue until it is explicitly closed.  The dialog is made through a permanent connection, allowing the client to send multiple messages to the server and allow the server to respond accordingly. It also allows the server to send asynchronous messages to the client.

Let's try a demo for persistent connection and hub:

Create a new ASP. NET MVC Project MVCAPPLICATIONSIGNALR, adding SIGNALR packages through NuGet.

Create a new class myconnection inherit from Persistentconnection, reference the SignalR namespace, override the Onreceivedasync method, and require SignalR to broadcast the incoming information

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Text;
Using SignalR;
Using System.Threading.Tasks;

Namespace MVCAPPLICATIONSIGNALR
{
public class Myconnection:persistentconnection

{
protected override Task Onreceivedasync (irequest request, String ConnectionID, String data)
{
Broadcast data to all clients
data = string. Format ("data is: {0} time is: {1}", Data, DateTime.Now.ToString ());
Return Connection.send (ConnectionID, data);
}

}
}

The corresponding routing information is then added to the Global.asax, which is handled by the SignalR routing table, which handles the output of the Metadata, and the red part of the code:

protected void Application_Start ()
{
Routetable.routes.mapconnection<myconnection> ("echo", "echo/{*operation}");

So the server side is done. Now we are in the Project master, View (Home/index), and then add the necessary code:

<meta charset= "Utf-8"/>
<title> @ViewBag .title</title>
<link href= "@Url. Content (" ~/content/site.css ")" rel= "stylesheet" type= "Text/css"/>
<script src= "@Url. Content (" ~/scripts/jquery-1.6.4.min.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/modernizr-1.7.min.js ")" Type= "Text/javascript" ></script>
<script src= "@Url. Content (" ~/scripts/jquery.signalr-0.5.2.min.js ")" Type= "Text/javascript" ></script >

@{
Viewbag.title = "Home page";
}
<script type= "Text/javascript" >
$ (function () {
var connection = $.connection (' echo ');

Connection.received (function (data) {
$ (' #messages '). Append (' <li> ' + data + ' </li> ');
});

Connection.start ();

$ ("#broadcast"). Click (function () {
Connection.send ($ (' #msg '). Val ());
});
$ ("#btnStop"). Click (function () {
Connection.stop ();
});
});

</script>
<input type= "text" id= "msg"/>
<input type= "button" id= "broadcast" value= "Send"/>
<input type= "button" id= "Btnstop" value= "Stop"/>
<ul id= "Messages" >
</ul>

This is how it works:

Let's show another feature of SignalR: The function of invoking the client's JavaScript script from the server side, and the requirement of this feature must be to implement a hub-like pattern, so we can see how to implement a hub-type SignalR application.

Adding a class chat to a project inherits from the Hub class (which is required by the hub application):

Using System;
Using System.Collections.Generic;
Using System.Linq;
Using System.Web;
Using Signalr.hubs;
Using System.Threading.Tasks;
Using System.Threading;

Namespace MVCAPPLICATIONSIGNALR
{
[Hubname ("Geffchat")]
public class Chat:hub
{
public void SendMessage (String message)
{
Clients.sendmessage (message);
}
}
}

The intent of this program code is to add the connection code to the collection of online users when connecting to the Hub, and so on, as we will invoke the client script according to the client's ID.

1. Hubname: This atttibute represents the client side to establish a proxy object for the corresponding server-side objects. With Hubname, the server-side class name is not tied to the client. If not set, the server-side class name is the Hubname default value.

2. Inherit hub: After inheriting the hub, many of the corresponding designs are not written, we just need to focus on how the client sends the request to the server Hub, how the server notifies the client.

3. public void SendMessage (String message), just like WebService Method or Pagemethod, client side through the proxy object, you can directly call the server side This method. A follow-up will describe how to use it on the page.

4. Clients attribute: represents all pages with Chat. The clients type is dynamic because it is directed to the JavaScript object.

5. Clients.sendmessage (message): On behalf of the server side, call the SendMessage method on clients, which is the JavaScript method.

6. Summary: The function of the Chat object is to present this message to all client pages when the client side invokes the SendMessage () method. To achieve the function of the chat room.

The service side is done, start making the client, also add the following HTML code on the Home/index page

<%--A very important reference, be sure to add, and before this line, must first refer to Jquery.js and signalr.js--%>
<script src= "@Url. Content (" ~/signalr/hubs ")" Type= "Text/javascript" ></script>

@{
Viewbag.title = "Home page";
}
<script type= "Text/javascript" >
$ (function () {
var connection = $.connection ('/echo ');

Connection.received (function (data) {
$ (' #messages '). Append (' <li> ' + data + ' </li> ');
});

Connection.start ();

$ ("#broadcast"). Click (function () {
Connection.send ($ (' #msg '). Val ());
});
$ ("#btnStop"). Click (function () {
Connection.stop ();
});

//Establish the object for the server-side hub class, note that the first letter of the geffchat is changed to lowercase
var chat = $.connection.geffchat;

       //Defines the client-side JavaScript function for the server-side hub, by means of dynamic Call all clients JavaScript function 
        chat.sendmessage = function ( message) { 
           //When the server side calls SendMessage, The message data for server push is rendered in wholemessage  
             $ (' #wholeMessages '). Append (' <li> ' + message + ' </li> ');  
        };

$ ("#send"). Click (function () {
Call the Hub object called the server side to pass #message data to the server
Chat.sendmessage ($ (' #message '). Val ());
$ (' #message '). Val ("");
});

Open the connection.
$.connection.hub.start ();

});

</script>
<input type= "text" id= "msg"/>
<input type= "button" id= "broadcast" value= "Send"/>
<input type= "button" id= "Btnstop" value= "Stop"/>
<ul id= "Messages" >
</ul>

<div>
<input type= "text" id= "message"/>
<input type= "button" id= "send" value= "Sent"/>
<div>
Chat Room Content:
<br/>
<ul id= "Wholemessages" >
</ul>
</div>
</div>

1. Refer to the JS file of JQuery and SignalR first.

2. An important step: Add a JS reference with the path to " root directory /signalr/hubs". SignalR will create the relevant JavaScript, placed here.

3. by $.connection. " Server-Side Hubname ", you can establish a proxy object to the hub. Note that the first letter should be lowercase.

4. Define the JavaScript function on the client side for server-side notifications, the example here is sendMessage.

5. When the Send button is pressed, call the server-side SendMessage () method, just pass the proxy object directly. Note that the first letter should be lowercase.

6. Remember to open the connection through $.connection.hub.start ().

Note: SINGALR will automatically generate a Siganlr/hub bridge JS., there is no problem with localhost testing on this machine. When deploying to IIS, a 404 error occurs because the IIS miscalculation may be a virtual directory ..., the workaround is to add a section in Web. config:

<!--Join this section--

<system.webServer>

<validation validateintegratedmodeconfiguration= "false"/>

<modules runallmanagedmodulesforallrequests= "true" >

</modules>

</system.webServer>

This is to watch others, my behavior is plagiarism, but for me to learn, this is only the first step

SIGNALR an integrated client and server library. Internal two object classes: Persistentconnection and Hub

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.