Signalr Quickstart using HTML5 + singalr to build a multi-machine collaborative drawing board (1)

Source: Internet
Author: User

Signalr is an integrated client and server library. browser-based clients and ASP. Net-based server components can be used for two-way multi-step dialogs. In other words, this dialog can exchange a single stateless request/response data without restriction; it will continue until it is explicitly closed. A dialog is made through a permanent connection. The client can send multiple messages to the server and the server can reply accordingly. It is worth noting that the server can also send asynchronous messages to the client. Similar to Ajax, it is based on existing technologies. Itself is a complex. Generally, signalr uses long polling of JavaScript to implement communication between the client and the server. After the emergence of websockets, signalr also supports websockets communication. Of course, signalr also uses the server's parallel task processing technology to improve the scalability of the server. It targets the entire. NET Framework Platform, and it is not limited to hosting applications.ProgramIt is also a cross-platform open-source project that supports more than 2.10 mono. It is considered to be another practical choice for Web APIs, but it is more effective than ASP in the online processing function of the server. net MVC web API is much better, and more importantly, it can be used on web form.

Client library in signalr (. net/JavaScript) provides the ability to automatically manage, developers only need to directly use the signalr client library, and its JavaScript library can be perfectly integrated with jquery, therefore, it can be directly connected with jquery or knockout. JS.

Signalr has two types of objects:

· Persistent connection (HTTP persistent link): Persistent connections are used to solve persistent connections. In addition, the client can request data from the server, and the server does not need to implement too many details, you only need to handle the five events provided in persistentconnection: onconnected, onreconnected, onreceived, onerror, and ondisconnect.

· Hub: Information exchanger, used to solve the realtime information exchange function. The server can use the URL to register one or more hubs. If you connect to this hub, the server can share the information sent to the server with all clients, and the server can call the client script. However, it is still not based on HTTP standards, so it looks amazing, but it is not so magical, but Javascript is stronger, so it can be executed in a way like eval () or dynamically interpreted, allowing JavaScript to dynamically load and execute method calls.

Signalr encapsulates the entire exchange of information very beautifully. both the client and the server use JSON to communicate with each other, and all the hub information declared on the server side, generally, JavaScript is generated and output to the client ,. net is dependent on proxy to generate proxy object, which is similar /. net remoting is very similar, while the proxy is internally converting JSON into an object, so that the client can see the object.

Here we will try a demo for persistent connection and hub:

Create an ASP. net mvc project mvcapplicationsignalr and add the signalr package through nuget.

Create a new class myconnection inherited from persistentconnection, reference 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 );
}

}
}

Add the corresponding route information to global. asax. This will process the output of metadata in the signalr route table, in red.Code:

Protected void application_start ()
{
Routetable. routes. mapconnection <myconnection> ("Echo", "Echo/{* operation }");

 

In this way, the server is complete. Now we can add the necessary code in the master and view (home/index) of the project:

<Head>
<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>
</Head>

@{
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>
<H2> @ viewbag. Message </H2>
<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 the result of running:

Next we will show another function of signalr: the server calls the Javascript script function of the client, and the requirement of this function must be the ready-made Hub mode, therefore, we can see how to implement a hub-type signalr application.

Add a class chat to the project to inherit from the hub class (this is the requirement of 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 purpose of this program code is to add the connection code to the collection of online users when connecting to the hub, which will be used later, because we will call the client script according to the Client ID.

1. hubname: This atttivity represents how the client creates a proxy object corresponding to the server object. Through hubname, the server class name will not be bound to the client. If no value is set, the default value of hubname is the class name on the server side.

2. inherit from the hub: After inheriting from the hub, many corresponding designs do not need to be written. We only need to focus on how the client sends a request to the hub of the server, and how the server notifies the client.

3. Public void sendmessage (string message), which is like WebService method or pagemethod. The client can directly call this method on the server side through proxy object. We will introduce how to use it on the page later.

4. Clients attribute: indicates all pages with chat. The clients type is dynamic, because it must correspond directly to JavaScript objects.

5. Clients. sendmessage (Message): indicates that the server calls the sendmessage Method on clients, that is, the JavaScript method.

6. Conclusion: The responsibility of the chat object is to send the message to all client pages after the client calls the sendmessage () method. To achieve the chat room function.

After the server is finished, start creating the client and add the following HTML code on the home/index page.

<% -- A very important reference. Before this line, you 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 ();
});

// Create an object corresponding to the Hub class on the server. Note that the first letter of geffchat must be changed to lowercase letters.
VaR chat = $. Connection. geffchat;

// defines the client-side JavaScript function for the server hub. Using dynamic, call the JavaScript function of all clients
chat. sendmessage = function (Message) {
// when the server calls sendmessage, the server pushes the message data, rendered in wholemessage
$ ('# wholemessages '). append ('

  • ' + message + '
  • ');
    };

    $ ("# Send"). Click (function (){
    // Call the hub object called the server and send # message data to the server
    Chat. sendmessage ($ ('# message'). Val ());
    $ ('# Message'). Val ("");
    });

    // Open the connection
    $. Connection. Hub. Start ();

    });

    </SCRIPT>
    <H2> @ viewbag. Message </H2>
    <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 = "send"/>
    <Div>
    Chat Room content:
    <Br/>
    <Ul id = "wholemessages">
    </Ul>
    </Div>
    </Div>

    1. Reference jquery and signalr JS files first.

    2. An important step: Add a JS reference with the path 「Root directory/Signalr/hubs」. Signalr creates related JavaScript and places it here.

    3. Use $. Connection. "hubname on server" to create a proxy object for the hub.Note that the first letter must be in lowercase.

    4. Define the JavaScript function on the client side for the server to notify. The example here is sendmessage.

    5. When you press the send button, call the sendmessage () method on the server side. You only need to directly use the proxy object.Note that the first letter must be in lowercase.

    6. Remember to open the connection through $. Connection. Hub. Start.

    Note: singalr will automatically generate a siganlr/hub bridge JS .., and there will be no problem in using localhost on the local machine. When deployed to IIS, The 404 error may occur because the misjudgment may be a virtual directory ..., The solution is to add a section in Web. config:

    <! -- Add the following section -->

    <System. webserver>

    <Validation validateintegratedmodeconfiguration = "false"/>

    <Modules runallmanagedmodulesforallrequests = "true">

    </Modules>

    </System. webserver>

    Refer:

    • Https://github.com/SignalR/SignalR/wiki/QuickStart-Persistent-Connections
    • Https://github.com/SignalR/SignalR/wiki/QuickStart-Hubs
    • Signalr-group communications
    • Http://www.thinqlinq.com/Post.aspx/Title/SignalR-and-Reactive-Extensions-are-an-Rx-for-server-push-notifications
    • Event broker using RX and signalr (Part 3: Event consumers)
    • Part 1: A fluent API
      Part 2: implementation
      Part 4: solving the scenario
    • Using HTML5 + singalr to build a multi-host collaborative canvas (1)
    • Create a real-time permanent persistent connection Asynchronous Network Application Using signalr
    • Signalr-Introduction to signalr-quick chat app
    • Signalr-push data to clients using ihubcontext
    • Signalr-publish data from win forms using hub proxies
    • Signalr-dependency Injection
    • Scaling signalr with redis
    • Asynchronous scalable Web applications with real-time persistent long-running connections with signalr
    • ASP. net mvc, signalr and Knockout based real time UI syncing-for CO working UIS and continuous clients
    • Sending configurications using ASP. NET signalr

    Instance code: mvcapplicationsignalr

    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.