ASP. MVC3 using SignalR for push

Source: Internet
Author: User
Tags dot net

First, Introduction

Signal is a Microsoft-supported HTML WebSocket framework that runs on the Dot NET platform. The main purpose of this is to implement a server proactive push (push) message to the client page so that the client does not have to resend the request or use polling technology to obtain the message.

Second, the realization mechanism

The implementation mechanism of SignalR is similar to. NET WCF or Remoting, and is implemented using a remote proxy. For specific use, there are two different purposes of interfacing:persistentconnection and Hubs, where Persistentconnection is a long-time Javascript poll (similar to Comet), Hub is used to solve the real-time information exchange problem, it is implemented using Javascript dynamic loading execution method. SignalR the entire connection, the information exchange process is very beautiful package, the client and the server side all use JSON to exchange data.

Third, implement the HUB server-side code

Create a new SignalR directory in the project where you add the ChatHub.cs file with the following contents:

namespace signaltutorial.signalr{    [Hubname ("chat")] public    class Chat:hub    {public        void Send (string ClientName, String message)        {            //var toselfinfo = "You had sent message" + message;            Caller.addsomemessage (ClientName, toselfinfo);            Call the AddMessage method on all clients            clients.addsomemessage (clientName, message);            Clients[context.connectionid].addsomemessage (clientName, data);}}}    

1), Hubname This feature is to let the client know how to establish a server-side corresponding service proxy object, if not set this attribute, the server-side service class name as the default value of Hubname;

2), Chat inherits from the hub, from the following hub interface diagram can be seen: The hub support to the initiator (Caller), all clients (clients), a specific set (group) push messages.

3), public void Send (string clientName, String message) This interface is called by the client through the proxy object;

4), clients is the Hub attribute, which represents all linked client pages, and it is dynamic as Caller, as it is directed to the Javascript object;

5), Clients.addsomemessage (clientName, message); Represents the Addsomemessage method of the server-side call client, which is a Javascript method that pushes messages to the client.

6), Summary: The service here is very simple, that is, when a client calls the Send method to send a message to the server, the server is responsible for the message broadcast to all clients (or to specific groups or specific clients, see masking code), in order to implement the function of the chat room.

Four, implement the Hub client code

Note: SignalR relies on jquery, so SignalR must be placed behind jquery, and hubs must be placed after SignalR.

Then add Hubchat Tab in the body section:

@model dynamic@{    viewbag.title = "Title";} <script src= "@Url. Content (" ~/scripts/hubdemo.js ")" Type= "Text/javascript" ></script><script type= " Text/javascript ">    $ (document). Ready (function () {    }); </script>

Add a new Javescript script to the Scripts directory: Hubdemo.js.    The contents are as follows: $ (function () {var myclientname = $ (' #Placeholder '). Val ();    Proxy created on the fly var chat = $.connection.chat; Declare a function on the chat hub so the server can invoke it chat.addsomemessage = function (clientName, message)    {writeEvent (' <b> ' + clientName + ' </b> said to everyone: ' + message, ' event-message ');    }; $ ("#broadcast"). Click (function () {///Call the chat method on the server Chat.send (Myclientname, $ (' #msg '). Val ()). Done (function () {console.log (' Sent message success! ')                            ;                            }). Fail (function (e) {Console.warn (e);    });    });    Start the connection $.connection.hub.start ();        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> ')    ); }});

I have run once, can run normally, persistent connection section, the next section is introduced again. If you find any problem, you can point out, thank you.

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.