ServerPush usage instance analysis in ASP. NET and serverpush instance analysis
This example describes the ServerPush usage in ASP. NET. Share it with you for your reference. The specific analysis is as follows:
What is ServerPush? The server "push" to the client is actually "persistent connection".
Only when a browser requests data from the server, the server responds to the browser and does not actively push data to the browser. This is a security consideration and improves the server performance, if the server actively pushes data to the browser, it must use ServerPush and other technical simulation implementation.
For example:
Two pages are used to send messages to each other and the messages are placed in the database.
/// <Summary> /// summary of ServerPush1 /// </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. executeN OnQuery ("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") // login, and continuously query and receive the data sent by the other Party {// do a simple example, using ServerPush1.ashx? Me = sean // send me a string me = context to the message sent to sean. 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); // not found, take a rest of MS to query again, so as to avoid the query pressure on the database and occupy the CPU resources of the WEB server continue; // next 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, an endless loop will occur and the same message is continuously output to the page. executeNonQuery ("delete from T_Msgs WHERE Id = @ Id", new SqlParameter ("@ Id", id); // create an anonymous object, store the queried data to 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); // return the request result in the json format break; }}} else {throw new Exception ("action error ");}}
<! DOCTYPE html>
I hope this article will help you design your asp.net program.