Server-to-client information push with AJAX+MSMQ (Message Queuing) +webservice

Source: Internet
Author: User
Tags httpcontext msmq

Demand:

Push to the client whenever the database has data updates

Soft demand:

1, the server resources are limited, the requirements of resource consumption as small as possible;

2, the project can be controlled, not to call third-party untrusted unstable method.

Existing examples:

1, 58 home Using the method is TCP long connection, the server pressure is large;

2, Redis, etc. to provide subscription push service, open source, but customized to the developer of their development language proficiency requirements, the author level does not reach

Final Solution:

Explain:

①② page Loads the first time the data is requested, returns data, loads, calls AJAX2

③ page load is the request, but there is no data at this time, so block, wait for other components insert Msg

④ after receiving new MSG, return value to Ajax2

⑤AJAX2 Call Ajax1

⑥AJAX1 Refreshing data

After block AJAX2 only consumes one thread on the server, resource consumption is minimal.

=================== below is the code =======================

1. File structure

2, RECEIVE.CS//MSMQ of the receiving class

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingsystem.messaging;namespacewebapplication1{ Public classReceive { PublicString receives () {varQueue =NewMessageQueue (@". \private$\msgqueue"); Queue. Formatter=NewXMLMessageFormatter (New string[] {"System.String" }                ); Message m=queue.            Receive (); returnm.body.tostring (); }    }}

2, send.cs//msmq of the transmission class

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingsystem.messaging;namespacewebapplication1{ Public classSend { Public stringCreate (String msg) {Try            {                if(! Messagequeue.exists (@". \private$\msgqueue") {messagequeue.create (@". \private$\msgqueue"); }                varQueue =NewMessageQueue (@". \private$\msgqueue"); Queue. Send (MSG,"Label"); return "OK"; }            Catch(Exception ex) {return "Error"; }        }    }}

3, mqgiver.asmx//Core WebService

usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.Services;usingWebApplication1;namespaceserver receives mq{/// <summary>    ///Summary description of Mqgiver/// </summary>[WebService (Namespace ="http://tempuri.org/")] [WebServiceBinding (ConformsTo=Wsiprofiles.basicprofile1_1)] [System.ComponentModel.ToolboxItem (false)]    //to allow the Web service to be called from the script using ASP. NET AJAX, uncomment the downstream. //[System.Web.Script.Services.ScriptService][Serializable] Public classMQGiver:System.Web.Services.WebService {[WebMethod] Public stringHelloWorld () {return "Hello World"; } [WebMethod] Public voidgivemsg () {Receive R=Newreceive (); String msg=r.receives (); String Json="{\ "msg\": \ ""+ msg +"\"}"; stringcallback = httpcontext.current.request["Jsoncallback"]; HttpContext.Current.Response.Write (Callback+"("+ Json +")"); } [WebMethod] Public voidGivedata () {String Json="{\ "msg\": \ "Ok\"}"; stringcallback = httpcontext.current.request["Jsoncallback"]; HttpContext.Current.Response.Write (Callback+"("+ Json +")"); }    }}

4. msgadd.aspx//simulation adds data to MSMQ

Front Code<%@ Page language="C #"autoeventwireup="true"Codebehind="MSGadd.aspx.cs"inherits="The server receives MQ. Msgadd"%><! DOCTYPE HTML Public"-//W3C//DTD XHTML 1.0 transitional//en" "HTTP://WWW.W3.ORG/TR/XHTML1/DTD/XHTML1-TRANSITIONAL.DTD">"http://www.w3.org/1999/xhtml">"Server"> <title></title>"Form1"runat="Server"> <div> </div> <asp:button id="Button1"runat="Server"onclick="Button1_Click"text="Button"/> <asp:textbox id="TextBox1"runat="Server"></asp:TextBox> <asp:label id="Label1"runat="Server"text="Label"></asp:Label> </form></body>//================================================Background CodeusingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingsystem.web;usingSystem.Web.UI;usingSystem.Web.UI.WebControls;usingWebApplication1;namespaceserver receives mq{ Public Partial classMSGadd:System.Web.UI.Page {protected voidPage_Load (Objectsender, EventArgs e) {        }        protected voidButton1_Click (Objectsender, EventArgs e) {Send S=NewSend (); Label1.Text=s.create (TextBox1.Text); }    }}

5. Call interface

"Jq.js"></script>"Text/javascript">function GetData () {$.ajax ({URL:"http://localhost:55843/MQGiver.asmx/GiveData?jsoncallback=?", DataType:"Jsonp", Success:onsuccess,}); function onsuccess (JSON) {$ ("#la"). Text (json.msg) getmsg (); }} function getmsg () {$.ajax ({URL:"http://localhost:55843/MQGiver.asmx/GiveMsg?jsoncallback=?", DataType:"Jsonp", Success:onsuccess1,});        function OnSuccess1 (json1) {GetData ();    }} getdata (); </script> <label id="La"> </label></body>

The whole project is like this, has been through, there are good suggestions and questions welcome message!

Server-to-client information push with AJAX+MSMQ (Message Queuing) +webservice

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.