This article is mainly for you to introduce in detail the. Net MVC implementation of long-polling related data, with a certain reference value, interested in small partners can refer to
What is long polling?
Long polling is a "server push" technology implementation of a way to transfer changes in the service to the client in real time, without the client to frequently refresh, send requests.
Long polling principle?
The client sends an AJAX request to the server, and after the server receives the request, it keeps the connection from returning the message until the relevant processing is complete before returning the response information and closing the connection, the client receives the response information, processes it, and then wants the server to send a new request.
Long polling application scenario?
Long polling is often used in web-timely communication, monitoring, real-time quote system and so on need to send changes in the service side to the client scene.
What are the pros and cons of long polling?
Advantage: No message is sent to the server frequently.
Cons: Server remains connected compare cost source
Realize:
Front Code:
In the callback, we call the function again so that it starts the next request after each request is closed.
<p id= "container" ></p><script type= "Text/javascript" > $ (function () { function Longpolling () { $.getjson ("/datetime/gettime", function (JSON) { $ ("#container"). Append (Json.date + "<br/ > "); Longpolling (); }); }; Longpolling (); }); </script>
Background code:
Our backstage controller. To use async, inherit the Asynccontroller base class
public class Datetimecontroller:asynccontroller {public void Gettimeasync () {// Timer, 5-second triggering of a elapsed event System.Timers.Timer timer = new System.Timers.Timer (5000); Tell. NET Next will be an asynchronous operation AsyncManager.OutstandingOperations.Increment (); The Elapsed event timer for the subscription timer. Elapsed + = (sender, E) = = {//Save the parameter to be passed to gettimecompleted asyncmanager.parameters["nowdate"] = E.sig Naltime; Tells the ASP. The asynchronous operation is complete and the Gettimecompleted method is called AsyncManager.OutstandingOperations.Decrement (); }; Start Timer timers. Start (); The public ActionResult gettimecompleted (DateTime nowdate) {return Json (new {date = Nowdate). ToString ("HH:mm:ss") + "Welecom"}, Jsonrequestbehavior.allowget); } }