Example analysis of ServerPush usage in ASP. NET

  • 2021-07-01 07:07:11
  • OfStack

This article illustrates the usage of ServerPush in ASP. NET. Share it for your reference. The specific analysis is as follows:

What is ServerPush? The server "pushes" to the client, which is actually a "long connection"

Only when the browser requests the server, the server will respond to the browser and will not actively push the data to the browser. This is a security consideration and a consideration for improving the performance of the server. If the server actively pushes the data to the browser, it will use ServerPush and other technologies to simulate the implementation.

For example:

It is realized by sending messages to each other through two pages, and the messages are put into the database.


/// <summary>
/// ServerPush1  Summary description of 
/// </summary>
public class ServerPush1 : IHttpHandler
{
  public void ProcessRequest(HttpContext context)
  {
   context.Response.ContentType = "application/json";
   string action = context.Request["action"];
   if (action == "send")// Send 
   {
    string me = context.Request["me"];
    string toUserName = context.Request["toUserName"];
    string msg = context.Request["msg"];
    SQLHpler.ExecuteNonQuery("INSERT INTO T_Msgs(FromUserName,ToUserName,Msg) VALUES(@FromUserName,@ToUserName,@Msg)", new SqlParameter("@FromUserName", me),
     new SqlParameter("@ToUserName", toUserName),
     new SqlParameter("@Msg", msg));
    context.Response.Write(new JavaScriptSerializer().Serialize(new { Status = "ok" }));
   }
   else if (action == "receive")
   // Log in, and continue to inquire and receive the data sent by the other party 
   {
    // Do 1 A simple example to ServerPush1.ashx?me=sean
    // Please send it to sean Send me the message 1 Article 
    string me = context.Request["me"];
    while (true)
    {
     DataTable dt = SQLHpler.ExecuteQuery("SELECT TOP 1 * FROM T_Msgs WHERE ToUserName=@ToUserName",new SqlParameter("@ToUserName", me));
     if (dt.Rows.Count <= 0)
     {
      Thread.Sleep(500);// Didn't find it, rest 500ms Re-query, so as to avoid the query pressure and occupation of the database WEB Server CPU Resources 
      continue;// Under 1 Times while
     }
     else
     {
      DataRow row = dt.Rows[0];
      long id = (long)row["Id"];
      string fromUserName = (string)row["FromUserName"];
      string msg = (string)row["Msg"];
      // Delete the message after the query, otherwise there will be an infinite loop, and the output to the page will be the same 1 Messages 
      SQLHpler.ExecuteNonQuery("DELETE FROM T_Msgs WHERE Id=@Id",new SqlParameter("@Id",id));
      // Create 1 An anonymous object, which stores the queried data in it 
      var data = new { FromUserName = fromUserName, Msg = msg, Id = id };
      string json = new JavaScriptSerializer().Serialize(data);// Converts an anonymous object to a json
      context.Response.Write(json);// Will the request result with json Format return 
      break;
     }
    }
   }
   else
   {
    throw new Exception("action Errors ");
   }
}


<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<script type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script type="text/javascript">
var rev = function () {
 var mine = $('#me').val();
 $.ajax({
  type: 'post', url: 'serverPush1.ashx',
  data: { action: 'receive', me: mine },// Pass to serverPush.ashx According to me Find and send me Message of 
  success: function (data) {
   $('#ulMsg').append($('<li>' + data.FromUserName + ' Say to me: ' + data.Msg + '</li>'));
   rev();// After receiving the message, request the data from the server and give it to me again 1 Message 
  },
  error: function () {
   rev();
   // Send the request again even if the network request fails (such as the user's network failure) 
  }
 });
};
$(function () {
 // Send 
 $('#btnSend').click(function () {
  var myName = $('#me').val();
  var toUserName = $('#toUserName').val();
  var msg = $('#msgContext').val();
  $.ajax({
   type: 'post', url: 'serverPush1.ashx',
   data: { action: 'send', me: myName, toUserName: toUserName, msg: msg },// According to the information input by the user, it is transmitted to the server ServerPush.ashx Perform an insertion operation 
   success: function (data) {
    if (data.Status == 'ok') {// If the send is successful, 
     $('#ulMsg').append($('<li> I'm right ' + toUserName + ' Say: ' + msg + '</li>'));
     $('#msgContext').val('');
    }
    else {
     alert(' Send error, return message unrecognized ');
    }
   },
   error: function () {
    alert(' Send error ');
   }
  });
 });
 // Log in and receive data 
 $('#btnLogin').click(function () {
  rev();
  $(this).attr("disabled", "disabled");
 });
 /*
 $('#btnLogin').click(function () {// Receive 
  var mine = $('#me').val();
  $.ajax({
   type: 'post', url: 'serverPush1.ashx',
   data: { action: 'receive', me: mine },
   // Pass to serverPush.ashx According to me Find and send me Message of 
   success: function (data) {
    $('#ulMsg').append($('<li>' + data.toUserName + ' Say to me: ' + data.msg + '</li>'));
   },
   error: function () {
    alert(' Receive failed ');
   }
  });
 });*/
});
</script>
</head>
<body>
  Sender: <input type="text" id="me" /><input type="button" id="btnLogin" value=" Landing " style=""/><br />
  Recipient: <input type="text" id="toUserName" /><br />
  Input message: <input type="text" id="msgContext" /><input type="button" id="btnSend" value=" Send " /><br />
  Chat record: <br />
 <ul id="ulMsg">
 </ul>
</body>
</html>

I hope this article is helpful to everyone's asp. net programming.


Related articles: