First, Introduction
The principle of comet push, implemented in ASP. NET MVC, is simple.
Server-side: Receives the server sends the AJAX request, the server side does not return, but will hold, until has the thing to inform the client, only then returns this request.
Client: Requests an asynchronous action, and sends another immediately when it receives a return.
Disadvantage: An ASP. NET processing thread will be occupied for a long time. But compared to polling, it saves bandwidth.
Example:
Create a new controller as follows:
//Comet Server Push controller (need to set noasynctimeout to prevent long-time request pending timeout error)[Noasynctimeout, sessionstate (sessionstatebehavior.readonly)]PublicClass Cometcontroller:asynccontroller//Asynccontroller that need to inherit from async{///<summary>///Asynchronous methods to handle client-initiated requests///</summary>PublicvoidIndexasync () {AsyncManager.OutstandingOperations.Increment (); asyncmanager.parameters["Info"] ="What's wrong"; AsyncManager.OutstandingOperations.Decrement (); }///<summary>/// send a response to the client when the asynchronous thread finishes//</summary>// <param name= " Token > Data package Object </param>// <returns></returns> public ActionResult indexcompleted (string info) { return Json (info, jsonrequestbehavior.allowget);}}
Look for a page and request this asynchronous action via Ajax:
<Html><Head><Title>ajax Test</Title><ScriptSrc= "/content/jquery-1.10.2.min.js"></Script><ScriptType= "Text/javascript">$(function() {Getcometserverpush ();})functionGetcometserverpush () {$.ajax ({cache:FalseUrl:‘/comet/index‘, Success:function(data) { $("#info"). HTML (data); Getcometserverpush (); } }); } </script>< Span style= "color: #0000ff;" ></head><< Span style= "color: #800000;" >body> <div Span style= "color: #ff0000;" >id= "info" ></></body< Span style= "color: #0000ff;" >></html>
The above example, if you have a breakpoint on the action, will not stop seeing the breakpoint in the loop. Indicates that the asynchronous client is constantly pushing. Of course, this example simply illustrates the principle of push.
Second, the application
Application: Monitor a TXT file on the server and, when there is a change, push the content to the client.
//Comet Server Push controller (need to set noasynctimeout to prevent long-time request pending timeout error)[Noasynctimeout, sessionstate (sessionstatebehavior.readonly)]PublicClass Cometcontroller:asynccontroller//Asynccontroller that need to inherit from async{///<summary>///Asynchronous methods to handle client-initiated requests///</summary>PublicvoidIndexasync () {AsyncManager.OutstandingOperations.Increment (); FileSystemWatcher FSW =NewFileSystemWatcher (); FSW. Filter ="123.txt";//Only monitor 123.txt file FSW. Path = Server.MapPath (@"/");//Set the monitoring path FSW. EnableRaisingEvents =True//Start monitoring//FileSystemWatcher has a problem that has been triggered several times, but not with this push example, so FSW is not resolved. Changed + = (Object source, FileSystemEventArgs e) = ={asyncmanager.parameters["Info"] = System.IO.File.ReadAllText (Server.MapPath (@"/123.txt"), System.Text.Encoding.Default);; AsyncManager.OutstandingOperations.Decrement (); }; }//<summary>/// When asynchronous threads are completed send a response to the client///</summary>// <param name= " Token > Data package Object </param>// <returns></returns> public ActionResult indexcompleted (string info) { return Json (info, jsonrequestbehavior.allowget);}}
ASP. NET MVC Comet push